Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You probably don't need a plugin to do this. First of all, the DOM itself is entirely event driven. You can use event delegation to listen to all events on the root node (a technique that jQuery live uses). To handle custom events as well that may not be DOM related, you can use a plain old JavaScript object to do the job. I wrote a <a href="http://vombat.tumblr.com/post/425704473/eventbus-with-mootools" rel="nofollow noreferrer">blog post</a> about creating a central event dispatcher in MooTools with just one line of code.</p> <pre><code>var EventBus = new Class({Implements: Events}); </code></pre> <p>It's just as easy to do in jQuery too. Use a regular JavaScript object that acts as a central broker for all events. Any client object can publish and subscribe to events on this object. See this related <a href="https://stackoverflow.com/questions/2625122/using-class-object-mootools-style-events-in-jquery">question</a>.</p> <pre><code>var EventManager = { subscribe: function(event, fn) { $(this).bind(event, fn); }, unsubscribe: function(event, fn) { $(this).unbind(event, fn); }, publish: function(event) { $(this).trigger(event); } }; // Your code can publish and subscribe to events as: EventManager.subscribe("tabClicked", function() { // do something }); EventManager.publish("tabClicked"); EventManager.unsubscribe("tabClicked"); </code></pre> <hr /> <p>Or if you don't care about exposing jQuery, then simply use an empty object and call <code>bind</code> and <code>trigger</code> directly on the jQuery wrapped object.</p> <pre><code>var EventManager = {}; $(EventManager).bind("tabClicked", function() { // do something }); $(EventManager).trigger("tabClicked"); $(EventManager).unbind("tabClicked"); </code></pre> <p>The wrappers are simply there to hide the underlying jQuery library so you can replace the implementation later on, if need be.</p> <p>This is basically the <a href="http://en.wikipedia.org/wiki/Publish/subscribe" rel="nofollow noreferrer">Publish/Subscribe</a> or the <a href="http://en.wikipedia.org/wiki/Observer_pattern" rel="nofollow noreferrer">Observer pattern</a>, and some good examples would be Cocoa's <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html" rel="nofollow noreferrer">NSNotificationCenter</a> class, <a href="http://www.dossier-andreas.net/software_architecture/eventbus.html" rel="nofollow noreferrer">EventBus</a> pattern popularized by Ray Ryan in the GWT community, and several others.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload