Skip to content

Event driven modules

Tim Branyen edited this page Jul 26, 2013 · 1 revision

Backbone-Boilerplate help you keep your module loosely coupled via the use of an EventManager.

Many design patterns are actually solutions to the problem of tight coupling. If two components are tightly coupled, it means that one component has direct knowledge of the other in such a way that a change to one of the components often necessitates a change to the other component.
[ ... ]
Loose coupling is achieved by limiting each component’s knowledge of the larger system. In essence, every component needs to be as dumb as possible to ensure loose coupling. The less a component knows, the better off the entire system tends to be.
Maintainable JavaScript by Nicholas C. Zakas (O'reilly)

Global EventManager

In Backbone-Boilerplate, this is achieved by encouraging the use of a global EventManager (an implementation of the pub/sub pattern). The app base module extend Backbone.Events exposing the same API. For example:

// Listening to events
define(function( require ) {
    var app = require("app");
    app.on("global:event", function() {
        console.log("global:event was fired");
    });
});

// Triggering events
define(function( require ) {
    require("app").trigger("global:event");
});

A good practice to prevent naming collision is to namespace every global events you send; like this: <namespace>:<event>.

Starting with Backbone 0.9.9, the global Backbone object is also an event manager and can be use the same way app can.

Local EventManager

If you need more separation between your modules, you can create a local event manager inside your modules, for example:

var eventManager = _.extend( {}, Backbone.Events );

new Parent({
    views: {
        ".child": new Child({ eventManager: eventManager });  
    }
});

You may also leverage LayoutManager views' event bubbling to manage UI based events.

Sources