سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

As Paul mentioned, all the backbone objects, including the Router, have the Event object extended, so you can set up event listeners on these. But I understand why you want to centralize the management of the events, so that you don't need to set up event listeners on various objects, or pass in an event aggregator.

Derick Bailey talks about this in the post below, and the solution he proposes is to create an App level event aggreagator.

http://lostechies.com/derickbailey/2012/04/03/revisiting-the-backbone-event-aggregator-lessons-learned/

Also, if you are doing anything more complex than the "to-do" application, I would encourage you to look at some of the Backbone frameworks, like Chaplin, Marionette, boilerplate etc. You can find the list here

In my application, I'm using the Marionette framework, and have found it really useful in creating modularized, easy to maintain code, with a lot of the usual repititive code already handled within it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top