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).
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.
You can use the Backbone. Model without jQuery, but Backbone.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With