Creating a Private Event Bus with jQuery

jQuery has a great API for working with DOM events – both native and custom. The great thing about its system is that you can also use it on regular objects, thus allowing you to quickly create private event systems for your application that don’t rely on DOM elements. In this post, I will show how I recently accomplished that by creating a private event bus for use on the Sharepoint MyBoard web app.

When building scalable apps or components the use of events helps keep functional code small and isolated while assisting in defining how that component interfaces or interacts with other components. The event system breaks the dependency from other components because it simply emits a signal “to all” listening indicating that a certain state or action was encountered. What those listening do based on that information we don’t care – that logic is built into the listening component.  Likewise, a component can listen for certain types of events in the Bus that it will use to mange and control its own functionally.

Let’s start with the end result and by writing down the desired API we would like out of the event bus.

Listen to events:


// Listen to events
events.on("eventName", callback)

// Remove an event listener
events.off("eventName", callback)

// Trigger  an event
events.trigger("eventName", [argsToPassAlong])

Pretty strait forward API.  So let’s create this with jQuery:


var bus = $({});

That’s it. I know this is going to look strange to you – you don’t normally see a JavaScript Object being passed into the jQuery constructor, but it’s a valid signature – http://devdocs.io/jquery/jquery#jQuery-object

So what we have above is a jQuery selection instance that has full access to all of jQuery prototype methods ($.fn).  It’s a bit overkill, but it works and it leverages the already available jQuery event system, which personally, I really like. Here is an example of it in action:

Example on jsbin.com

Hope you found this helpful.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s