Categories
backbone.js

Backbone.js: event aggregation and AMD

Great pattern to decouple your modules, and still have clean mechanism to communicate between them.

1) Create a generic “Notifier” module:

define([
‘underscore’,
‘backbone’
], function(_, Backbone) {
var notifier = _.extend({}, Backbone.Events);
return notifier;
});

2) In the two + views or models that you want to connect, include the notifier via your AMD arguments:

define([‘jquery’,’underscore’,’backbone’,’notifier’], function ($,_,Backbone,Notifier) {

}

3) Once your notifier is included that way, to subscribe and listen to events, all you have to do now is bind to the events you would like to listen to:

initialize: function () {
Notifier.on(‘helloEvent’, function (e) { alert(‘The main view says: ‘ + e)}, this)
},

4) To trigger events and push them to the notifier (from other modules), you just have to trigger them:

events: {
“click .clickme”: “sendEventOut”
},
sendEventOut: function () {
Notifier.trigger(‘helloEvent’,’I said hello’);
}

That’s it! Now two different views (or models, or collections) can communicate back and forth via triggered events, and even pass arguments between them.

2 replies on “Backbone.js: event aggregation and AMD”

Cool, but the only problem with this is that AMD is also about loading modules asynchronously, which means the listener module (publisher) may not be loaded yet and the trigger would fire into the ozone. The notifier should ensure that the module is loaded before firing the trigger.

I’m trying to implement a solution to handle this scenario now.

Thanks Randy,

That is correct. So far the event communication I’ve been needing happens as user interaction, meaning after everything has been loaded.

But there was a time where I run into that issue. In order to overcome it, I made the receiving view to also throw an event when it has been loaded and ready. And then bind the sender to send only after that handshake event is received. Something like:

Sender -> subscribe to event A
Receiver -> as soon as it loads, triggers event A
Sender gets event A, and knowing Receiver is loaded, sends event B

Event B is the one that needed to be sent to start with, event A was just the handshaking. It is not too elegant, but it works. Hope it helps!

Leave a Reply

Your email address will not be published. Required fields are marked *