Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js global events

Tags:

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).

like image 321
crawf Avatar asked Apr 06 '12 10:04

crawf


People also ask

Is backbone a MVC?

Backbone is a JavaScript MVC library and that's a key difference. In the JavaScript MVC context, a framework usually means that you need to configure your code to get things done.

Does backbone need jQuery?

You can use the Backbone. Model without jQuery, but Backbone.


1 Answers

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");
like image 161
Derick Bailey Avatar answered Sep 28 '22 16:09

Derick Bailey