Skip to content

Instantly share code, notes, and snippets.

@addyosmani
Created February 4, 2012 19:37
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save addyosmani/1739667 to your computer and use it in GitHub Desktop.
Save addyosmani/1739667 to your computer and use it in GitHub Desktop.
Backbone.js global pub/sub

Generally one implements notifications by listening for events on specific models but if one wishes to have a single global message interchange, it could be done as follows:

var pubsub = new Backbone.Model;

View1 = Backbone.View.extend({
  initialize: function(){
    pubsub.bind('custom event', callback);
  }
  // ...
});

View2 = Backbone.View.extend({
  // ...
  foo: function(){
    pubsub.trigger('custom event', data);
  }
});

or the reverse if one wished to publish events from models or collections.

@davej
Copy link

davej commented Mar 18, 2012

Thanks!

You might want to change 'custom event' to 'custom:event' or something similar because the code above will actually trigger the callback twice; once for the custom event and again for the event event.

@steckel
Copy link

steckel commented Mar 26, 2012

Any particular reason you prefer making the pubsub object a new instance of a Backbone.Model object over cloning the Backbone.Events object? Not sure if there is performance reasons or syntax preference...

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

View1 = Backbone.View.extend({
  initialize: function(){
    pubsub.bind('custom:event another:event', callbackForTwoEvents, this);
  }

  callbackForTwoEvents: function(data) {
    console.log(data);
  }
  // ...
});

View2 = Backbone.View.extend({
  // ...
  foo: function(){
    pubsub.trigger('custom:event', data);
  }
});

View3 = Backbone.View.extend({
  // ...
  bar: function(){
    pubsub.trigger('another:event', data);
  }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment