Backbone.js global events

2019-02-01 21:32发布

问题:

A quick question regarding Events in Backbone - is there any way to define a set of global events, which can be re-used in different views?

For instance - say I have several Views which are rendered on the page. Each View has a button that will expand a menu. There are also several other generic elements and events. Without putting this event logic into each View, is there a way that each of these Views could inherit, or pull these events from a global events definition? It would certainly save time and be a lot cleaner solution by defining these generic events in one place.

I've seen terms such as Event Aggregator and Factory patterns thrown around - but not sure on the best approach (or if they will achieve what I'm after).

回答1:

You're basically describing an event aggregator or dispatcher, yes. I've got a couple of articles on building and using them with Backbone:

http://lostechies.com/derickbailey/2011/07/19/references-routing-and-the-event-aggregator-coordinating-views-in-backbone-js/

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

And there are plenty more articles around the web for doing the same with Backbone and other pub/sub libraries.

It's quite simple to do in Backbone:


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

and now you have a vent object that can be used as an event aggregator throughout all of your application's views and other objects.


vent.on("some:event", function(){
  console.log("some event was fired");
});

vent.trigger("some:event");


标签: backbone.js