Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

EventBus

Matt Sweetman edited this page · 3 revisions

EventBus

EventBus is simply an object with event dispatching capabilities. It's designed to be used as a singleton, meaning whenever you require the EventBus module you get the same object every time. This allows it to be used as a centralized point of communication across your app.

Basic usage

The following example shows you how two separate modules can communicate using the EventBus:

Module-A:

var EventBus = require('EventBus');

EventBus.on('appPaused', function() {
  console.log('appPaused');
});

Module-B:

var EventBus = require('EventBus');

function onPauseButtonClick() {
  EventBus.trigger('appPaused'); // Module-A will log 'appPaused'
}

The benefit of this approach is that each module doesn't have to know about the other. They could be in two completely different areas of the app. One of them may not get created till long after the other. Using EventBus keeps dependencies to a minimum and enforces the principle of separation of concerns.

Namespacing events

Event names can have multiple levels of specificity by separating the name with colons, eg: user:logon or user:logoff. This idea is borrowed from Backbone.Model's change:propertyName convention. The following example should help explain it in more detail:

EventBus.on('pause:music', function() {
  console.log('pause:music');
});

EventBus.on('pause', function() {
  console.log('pause');
});

// This will call both the 'pause:music' and 'pause' event listeners
EventBus.trigger('pause:music');

// This will call 'pause' but not 'pause:music'
EventBus.trigger('pause:animation');

As per Backbone.Model the more specific events are triggered first. For example: EventBus.trigger('one:two:three') will trigger 3 events in the following order: one:two:three, one:two and one.

Something went wrong with that request. Please try again.