Search code examples
javascriptbackbone.jsclient-sidesinglepage

backbone.js Backbone.Events Prototype Router Event aggregation


What's the best way to make this eventAggregator (Backbone.View.prototype.eventAggregator = _.extend({}, Backbone.Events);) object available to my router in Backbone.js without passing it as a parameter.

I have a mainController (a view with no render) where I'm instantiating Backbone.View.prototype.eventAggregator.

I'm also creating my router inside of mainController but only View's will have the eventAggregator and not the router.

I don't want to go farther up and do Backbone.prototype.eventAggregator so that the router can have it. Is there a cleaner way of doing this?


Solution

  • Backbone has something like this already built in that you could use (from Backbone source):

      // Allow the `Backbone` object to serve as a global event bus, for folks who
      // want global "pubsub" in a convenient place.
      _.extend(Backbone, Events);
    

    Then in router:

    Backbone.trigger('something');
    

    And in view:

    this.listenTo(Backbone, 'something', this.someMethod);
    

    Or the other way around depending on what you are trying to do.