In Reactjs, how to trigger and respond to a user defined event? - javascript

I know you can do the following in render to handle click event, but how to respond to a user defined event, such as "newUserAdded".
<button onClick={this.handleAddNew}> Add Friend </button>
Here is what I mean by example:
var ele = document.getElementsByTagName('body')[0];
var myEvent = new Event('newUserAdded');
ele.addEventListener('newUserAdded', function () {alert('newUserAdded triggered')});
ele.dispatchEvent(myEvent);
// then you get an alert message
// how to do this in reactJS?
I am thinking of the following way to send message among React components:
var User = React.class({
...
emitNewUserEvent: function (e) {
// trigger the new user added message
// how?
},
...
});
Var DropDownSelection = React.class({
// in this component, I'd like to respond to 'NewUserAddedEvent' to add
// the newly added user to drop down list
// how?
});
Please advise! Thanks!

Related

How to inherit Odoo's POS buttons

I'm trying to add some functions in the POS buttons, specifically the button that shows up like "Validate". To test if the guide in this link https://odoo-development.readthedocs.io/en/latest/dev/pos/gui.html works, I'm just adding a console.log like the following:
odoo.define('my_module.js_file', function (require) {
"use strict";
var screens = require('point_of_sale.screens');
screens.PaymentScreenWidget.include({
init: function(parent, options) {
this._super(parent, options);
//My console log message
console.log('Hello world!')
this.pos.on('updateDebtHistory', function(partner_ids){
this.update_debt_history(partner_ids);
}, this);
},
});
But the message only shows up once when the POS ends loading the data and not when I push the button. What am I doing wrong here?
To add your code to the Validate button you will need to modify the payment screen widget via the include method (You already did that).
If you inspect the button from the browser you will find that it has a class next which is used to bind an event handler to the click JavaScript event.
Example:
var screens = require('point_of_sale.screens');
var PaymentScreenWidget = screens.PaymentScreenWidget;
PaymentScreenWidget.include({
validate_order: function(force_validation) {
console.log('Hello world!');
this._super(force_validation);
},
});

How to fireEvent outside of ConsumeEvent function in icCube web-reporting

i would like do a simple fireEvent("Refresh","")
from javascript outside of consumeEvent function.
as i want to be able to do a setinterval that would fireEvent "Refresh"
and put the event name inside a table 'do refresh query' in the web reporting
so eventually the table will refresh itself every 1 minute for example.
(i want to be able to refresh every table i have in the dashboard separately with different time interval)
the problem is that i'm able to do fireEvent only from the consumeEvent function
and then use context.fireEvent("Refresh","") but this can happen every time i have a different event occurring from the dashboard and it's not good enough
Event could be thrown anywhere with context's event manager instance:
<script type="text/javascript">
context.eventMgr().fireExternalEvent("eventName", eventValue)
</script>
Also you can fire events if you have access to ic3Reporting instance:
for example:
var ic3Application = ic3.startReport(options);
In that case you can fire app events in such way :
<script type="text/javascript">
//get ic3application instance
var ic3Application = ic3.startReport(options);
setInterval(function(){
ic3Application.fireEvent('table1-refresh', {})
},60000)
setInterval(function(){
ic3Application.fireEvent('table2-refresh', {})
},120000)
</script>
Then just set event names to "do Refresh Query" tables' event.
UPDATE
Version of script inside ic3report.html
<script type="text/javascript">
var ic3root = "../"
var ic3rootLocal = "../"
var options = {
root: ic3root,
rootLocal: ic3rootLocal,
callback: function () {
$('#intro').remove();
var options = {
<!-- ic3-start-report-options (DO NOT REMOVE - USED TO GENERATE FILES) -->
};
var ic3Application = ic3.startReport(options);
setInterval(function () {
ic3Application.fireEvent('ic3-table', {})
},20000)
};
ic3ready(options);
</script>
UPDATE
Here is a report with an example.

Backbone Event Triggering a Popup getting blocked.

I'm having an issue where I want to call GET on an endpoint, and based on the result of that, either render a modal or follow a link.
Currently, when I get the click event, I disable the default behavior of the anchor tag (I don't want to redirect before I check the result.).
I do a GET on the endpoint and throw an event from the callback if one of the return parameters is true. This event has a listener on it that
will trigger rendering and displaying the modal.
The issue with this methodology is: The GET callback doesn't allow me to redirect to the link unless I disable popup blockers and I would like my
users to have a good user experience.
I'm debating between a polling strategy (non-performant, not always accurate) or having the click event open a window that will either follow the anchor tag
or render the modal.
Would appreciate any other ideas or suggestions. Thanks!
Template is defined as follows:
var template = _.template('\
<a href="<%-linkUrl%>?fromHome=true" draggable="false" data-type="app-button" data-se="app-button" target="_blank" \
class="app-button">\
<img draggable="false" src="<%-logoUrl%>" class="logo">\
<span data-action="show-settings" class="icon-button <%-showIcon%>">\
<span class="icon icon-settings-dark"></span>\
</span>\
</a>\
<p class="app-button-name" data-se="app-button-name"><%-label%></p>\
');
Events are defined as follows:
events: function () {
var events = {};
events['click [data-type=app-button]'] = '_firstLoginSettings';
return events;
},
Now here's the function itself being called.
_firstLoginSettings: function (e) {
if (this.model.get('__notVerified__')) {
this.state.trigger(Events.SHOW_CONFIRMATION, this.model);
} else {
e.preventDefault();
e.stopPropagation();
this.state.trigger(Events.CHECK_VPN_DIALOG, this.model);
}
},
I have a listener on my main router.
this.listenTo(this.state, Events.CHECK_VPN_DIALOG, this._checkVpnDialog);
And here's the rest of the router code:
_checkVpnDialog: function (appLink, appLinkSettings) {
var self = this;
var vpnSettings = new VpnSettings({
appLink: appLink,
'__appInstanceId__' : appLink.get('__appInstanceId__')
});
vpnSettings.fetch({}).done(_.bind(function(vpnSettings) {
if (vpnSettings.checkVpn) {
self.state.trigger(Events.SHOW_VPN_DIALOG, appLink);
} else {
appLink._firstLoginSettings();
//This doesn't work because it's not associated with a user action, so it won't let me open this window. This isn't part of the click event loop any more.
var linkUrlTemplate = _.template('<%-linkUrl%>?fromHome=true');
window.open(linkUrlTemplate({linkUrl: appLink.get('__linkUrl__')}));
}
}));
},
_showVpnDialog: function (appLink, appLinkSettings) {
this.credsDialog && this.credsDialog.remove();
if (!appLinkSettings) {
appLinkSettings = new AppLinkSettings({
id: appLink.get('id'),
'__tab__': appLink.get('__tab__')
});
appLinkSettings.fetch().done(_.bind(this._renderVpnDialog, this, appLink, appLinkSettings));
} else {
this._renderVpnDialog(appLink, appLinkSettings);
}
},
_renderVpnDialog: function (appLink, appLinkSettings) {
if (appLink.get('__needsVpn__')) {
this.vpnDialog = new VpnDialog({
model: appLink,
appLink: appLink,
settings: this.settings,
state: this.state
});
this.vpnDialog.render();
}
},
So what I did instead was to open a new window with the click, and then change the location of the window so it would either go to the new location or close itself. Kind of a hacky solution, but it works!

how to wait for loading data into the store

There are menu button ("clients"), tree panel with clients list (sorted by name) and viewer with selected client details. There is also selectionchange action..
My task - on button click switch to client view and select and load details for first client every time button has been clicked. My problem - store is not loaded, how waiting until ext js will autoload data to the store?
my controller code:
me.control({
'#nav-client': {
click: me.onNavClientClick
},
...
'clientlist': {
// load: me.selectClient,
selectionchange: me.showClient
}
});
onNavClientClick: function(view, records) {
var me = this,
content = Ext.getCmp("app-content");
content.removeAll();
content.insert(0, [{xtype: 'clientcomplex'}]);
var first = me.getClientsStore().first();
if (first) {
Ext.getCmp("clientList").getSelectionModel().select(me.getClientsListStore().getNodeById(first.get('clientId')));
}
},
...
Two main questions:
is it good solution in my case? (to select first client in tree panel)
var first = me.getClientsStore().first();
// i use another store to get first record because of i dont know how to get first record (on root level) in TreeStore
...
Ext.getCmp("clientList").getSelectionModel().select(me.getClientsListStore().getNodeById(first.get('clientId')));
i know this code works ok in case of "load: me.selectClient," (but only once),
if i place this code on button click - i see error
Uncaught TypeError: Cannot read property 'id' of undefined
because of me.getClientsListStore() is not loaded.. so how to check loading status of this store and wait some until this store will be completely autoloaded?..
Thank you!
You can listen the store 'load' event. Like this:
...
onNavClientClick: function(view, records) {
var me = this;
// if the store isn't loaded, call load method and defer the 'client view' creation
if (me.getClientsStore.getCount() <= 0) {
me.getClientsStore.on('load', me.onClientsStoreLoad, me, { single : true});
me.getClientsStore.load();
}
else {
me.onClientsStoreLoad();
}
},
onClientsStoreLoad : function () {
var me = this,
content = Ext.getCmp("app-content");
content.removeAll();
content.insert(0, [{xtype: 'clientcomplex'}]);
var first = me.getClientsStore().first();
if (first) {
Ext.getCmp("clientList").getSelectionModel().select(me.getClientsListStore().getNodeById(first.get('clientId')));
}
},
...

how should i refer to the calling object within a handled keyboard event in javascript

hi I am writing a javascript widget which handles keyboard events. The issue in question arises when i show a div and want to hide it when someone presses esc.
what's the best way to achieve the following (i am using jquery in this project )
var escToExit = function(e){
// code to check for esc
// i then want to call the instance of widget that is linked to this function
}
var widget = {
show : function(){
$(document).keyup(escToExit);
},
hide : function(){
//hide code here
}
}
thanks
Edit
By value:
var escToExit = function(e){
e.data.wpass; // here is your ref
// rest of func
}
var widget = {
show : function() {
$(document).bind('keyup', {wpass : widget}, escToExit);
// rest of obj
}
See
http://api.jquery.com/bind/
and
http://api.jquery.com/trigger/

Categories

Resources