Skip to content

Instantly share code, notes, and snippets.

@addyosmani
Last active December 15, 2015 01:59
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save addyosmani/5183962 to your computer and use it in GitHub Desktop.
Save addyosmani/5183962 to your computer and use it in GitHub Desktop.
Mediator with Backbone 0.9.10

The Mediator pattern enables communication (mediation) between views using a mediator object.In the latest version of Backbone, the Backbone object itself can be used as a mediator without the need of a seperate helper.

In the following example, triggerSomething in our ToolbarView uses the global event-bus on the Backbone object to broadcast an application wide event somethingHappened with data.

// First view
var ToolbarView = Backbone.View.extend({
  className: ".toolbar",
  events: {
    "click .button":   "triggerSomething"
  },
  
  triggerSomething: function(){
    Backbone.trigger('somethingHappened', { id: 2 });  
  },
  render: function() {
    ...
  }
});

In TableView, we then subscribe to the global somethingHappened event in our view initialization using Backbone.on(), executing some behavior whenever we are notified of a change. We are able to similarly unsubscribe in our view destruction using Backbone.off():

// Second view
var TableView = Backbone.View.extend({
    
    initialize: function () {
        Backbone.on('somethingHappened', onSomething);
    },
    
    render: function(){
      // ...  
    },
    destroy: function () {
        Backbone.off('somethingHappened', onSomething);
    },

    // Action when something happens.
    onSomething: function (data) {
        console.log('Received:' + data.id);
    }
});

The more recent listenTo method may also be used for the same purpose.

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