I am looking for a way to dispatch events globally and inside requireJS modules using javascript or jquery.
I would like to be able to say within my js files:
dispatchEvent(myCustomEventWithSomeData);
and then in some other part of the application add a listener like so:
addEventListener(“type Of Event”, executeThisFunction);
is this possible using jquery? Or any other means? And will a potential solution work within requireJS modules which are not global javascript objects?
Also, How can I create an event that bubbles. So that if I want an event to execute only in a specific section of the code it is not dispatched globally?
Yes, this is something I typically setup very early within my own applications. Now, how you deal with your events is going to be very dependent on what library or techniques you decide to use, but the core concepts will remain the same.
Personally, I think PostalJS is the cock of the walk, so I'm going to use that as an example here. I'm not going to include too much code because it would be mostly ceremony and boilerplate, but I hope you'll get the idea.
One, you'll want to create something like a global App object for your events to rest on. Overall this is a good practice when modularizing your JS code - you'll want something which acts as a broker between modules. It can be very plain and basic:
define(function() {
var App = {};
return App;
});
Now, this module should be loaded into something which begins to populate it. You can get away with not doing this, for a while, but I find eventually circular dependencies tend you bite you in the ass. So I recommend including this in something akin to your "main" module. From there, include your event system and add it to App.
define(['app', 'events'], function(App, Events) {
App.events = new Events();
});
Now you have a nice, lightweight object you can include in other modules which shares the same Events object. So lets say you have a sidebar:
define(['app'], function(App) {
// User has clicked the sidebar
App.events.publish('sidebar.clicked'); //
});
And, oh I don't know, perhaps clicking the sidebar makes a dinosaur appear, so in your dinosaur module, you'd listen/subscribe by doing the following:
define(['app'], function(App) {
App.events.subscribe('sidebar.clicked', showDinosaur);
});
Having a lightweight object you can share between modules I've found is key to a successful modularized JS architecture. I use this in my own projects as a global object store, a container for my WebSocket messaging layer, and other things I don't want to need to explicitly include individually in each module.