One way of emitting events is by using trigger on a jQuery element.
This is okay if we only wanted to trigger an event from a specific element, but what happens if we want a generic way of doing things, such as without referring to an element when triggering?
The way to do this is to use jQuery.Callbacks() to create a pubsub system.
An instance of jQuery.Callbacks accumulates functions, and runs one functions after another when the “fire” method is call upon. The property of jQuery.Callbacks that is of interest in the pubsub system, is the ability to fire(call) the functions when needed, whereas the ability to accumulate multiple functions is not as critical to the pubsub system.
To demonstrate pubsub, our example will have three select lists, where each subscribes and publishes to one another.
The code from the jQuery api page will be used
//Adapted from jQuery api page (only variable renames)
The main point of this code, is that ‘pubsubNameSpace’ will create a namespace for a string that is passed in as ‘id’. The ‘id’ is a key in the ‘classGroups’ object. The ‘classGroup’ is an object that is the return value of ‘pubsubNameSpace’ which has a ‘publish’, ‘subscribe’, and ‘unsubscribe’ key that refer to the jQuery Callbacks methods.
Once we have this code, the following can be called like so
//Create a namespace
When publishing, one can pass in any data, but with the subscribe call, a function must be use as a funnel for the data that has been published.
To start the example, the initial variable declarations:
var $select = $('select.classy'),
The class name of the select lists is used as the name space for the pubsub. ‘$info’ is the div for displaying messages.
The main logic for publishing and subscribing for the select lists.
var id = -1;
Iterate through each select list and associate them with an id. Attach a ‘change’ event handler to each list and within it, publish the selected value with the select list id. Also subscribe to messages from the same class.
Now finally for subscribe’s function
//Log info for subscribe function
Note that there needs to be a check for whether or not the published data id is the same as the current list element’s id to ensure that our list does not listen to its own published message. This is because all select lists listens subscribe to the same class namespace.