我们也可以这样做。具有管理每个事件之间的空间的优势。
Github 在这里提交
直接将其添加到 Backbone 中:
delegateEvents: function(events) {
events || (events = _.result(this, 'events'));
if (!events) return this;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method)) method = this[method];
if (!method) continue;
var match = key.match(delegateEventSplitter);
this.delegate(match[1], match[2], _.bind(method, this));
}
return this;
}
覆盖委托事件方法:
Backbone.View.prototype.originalDelegateEvents = Backbone.View.prototype.delegateEvents;
Backbone.View.prototype.delegateEvents = function(events) {
events || (events = _.result(this, 'events'));
if (!events) return this;
this.undelegateEvents();
for (var key in events) {
var method = events[key], combinedEvents = key.split(',');
if (!_.isFunction(method)) method = this[method];
if (!method) continue;
for(var i = 0, match = null; i < combinedEvents.length; ++i) {
match = combinedEvents[i].trim().match(/^(\S+)\s*(.*)$/);
this.delegate(match[1], match[2], _.bind(method, this));
}
}
return this;
};
我们现在可以在一行中管理事件:
events: {
'click a[data-anchor], wheel, keydown': 'scroll'
}