What is the best way to bind events to a Backbone boilerplate application? I’ve been trying to bind my events directly to the models associated with my views, in my views, but it doesn’t seem to be working. I see within ‘namespace.js’, that there is an app key that extends Backbone.Events like so:
// Keep active application instances namespaced under an app object.
app: _.extend({}, Backbone.Events)
I don’t fully understand how to use it…
I was able to get things working without the boilerplate, but it does provide some very cool functionality, so I’d love to be able to use it. Thanks!
ADDED
the code I was using was with the underscore bind method like so:
this.module.bind('change', this.render);
But then, I realized that ‘this.model’ is returning undefined, and so this doesn’t work. I really am not sure how the boilerplate wants me to reference my model from the view.
I’m not sure if it is a typo that you copied from your code or a typo you only entered here, but I believe
this.module(which IS undefined) should bethis.model, which you also must be sure to pass in when you instantiate your view, of course, as so:myView = new BBView({model: myModel});then you can say
this.model.bind('change', this.render);orthis.model.on('change', this.render);for the most recent version of BackboneI frequently bind my views to change events on my models in this way.
As for extending Backbone.Events, the way I have used it is to create an independent “event aggregator” that will help connect events between different views on your page. Let’s say for example you have some action on one view that needs to set off an action on another view. In this case, you can pass your event aggregator object as an option to each of your views when you instantiate them, so that they can both trigger events or bind to events on a common object (i.e. your event aggregator).
whatsUp = _.extend({}, Backbone.Events) // the aggregatormyFirstView = new FirstBBView ({whatsUp: whatsUp});(the aggregator shows up as
this.options.whatsUpinside the view)mySecondView = new SecondBBView2 ({whatsUp: whatsUp});inside FirstBBView:
this.options.whatsUp.bind('specialEvent', function(arg1,arg2) {// do stuff
});
inside SecondBBView, when something important happens:
this.options.whatsUp.trigger('specialEvent', {arg1: 'some data', arg2: 'more data'});For a great explanation, see this great article by Derick Bailey