How can I add dynamic events in my view class in Backbone.js
I have a View Class with
var myViewC开发者_开发问答lass = Backbone.View.extend({
events: {
'change select': 'changeSelect',
'click a.changeLink': 'clearSelect'
},
initialize: function() {
this.delegateEvents({'click select': 'changeSelect'});
},
.
.
.
});
This is adding {'click select': 'changeSelect'} event, however somehow {'click a.changeLink': 'clearSelect'} doesn't woek.
anybody knows the solution?
Thanks, Rohan
Backbone automatically delegates events from the events attribute of your view. You are overrriding the previously delegated events. You can call $(this.el).delegate(...) but you can also do
this.delegateEvents(_.extend(this.events, {'click select': 'changeSelect'}));
Since I'm doing this a lot, here is my tiny Backbone extension (based on Julien's answer and my testing):
Backbone.View.prototype.addEvents = function(events) {
this.delegateEvents( _.extend(_.clone(this.events), events) );
};
Use:
BaseResizable.View = Base.View.extend({
initialize: function() {
Base.View.prototype.initialize.call(this);
this.addEvents({
'resizestop': 'resizeStop'
});
},
resizeStop: function(event, ui){...}
}
You will have to do addEvents()
again if you use undelegateEvents()
.
精彩评论