我有一个带有足够简单的事件对象的 View (在 CoffeeScript 中,因为它很甜)
APP.bb.Recipe_Index = Backbone.View.extend
template: JST['templates/Recipe_Index']
el: $ "#recipes"
events:
'click a' : 'testFunction'
testFunction: () ->
console.log 'test called'
return 'this function'
我的事件没有绑定(bind)。当我到达未缩小的 0.5.3 Backbone.js 文件中的第 967 行时
delegateEvents : function(events) {
//snip
for (var key in events) {
var method = this[events[key]];
if (!method) throw new Error('Event "' + events[key] + '" does not exist');
var match = key.match(eventSplitter);
var eventName = match[1], selector = match[2];
method = _.bind(method, this);
eventName += '.delegateEvents' + this.cid;
if (selector === '') {
$(this.el).bind(eventName, method);
} else {
$(this.el).delegate(selector, eventName, method); <-- THIS ONE
}
}
},
当我在 Chrome 中设置断点时,它最终会出现错误的 jQuery 语法:
selector == 'a'
eventName == click.delegateEventsview8'
method == 'function() {[native code]}'
选择器是正确的,但我不确定为什么在第 963 行上有一个附加到我的“click”字符串,它指示事件类型。该方法在与下划线绑定(bind)之前读取为我的 console.log
方法,因此这是正确的。
最终结果是我的事件没有被触发。想知道我在这里连接错了什么。
最佳答案
事件名称click.delegateEventsview8
实际上是jQuery事件的正确值。 Backbone 使用 jQuery 的命名空间事件功能。 (You can read more about it here)
Backbone 使用命名空间事件,因此它可以轻松解除绑定(bind)在其 undelegateEvents
函数中添加的所有事件。通过使用命名空间,Backbone 可以确保它只解除其添加的事件的绑定(bind)。这样它就不会解除绑定(bind)任何未添加的事件。
undelegateEvents : function() {
$(this.el).unbind('.delegateEvents' + this.cid);
},
至于为什么事件没有被触发,我不知道。
在模板渲染到 View 的 el
后,尝试在渲染方法中手动添加单击事件,然后查看它是否被调用。如果没有,那么您就知道选择器有问题。
render: function() {
$(this.el).append(//your template code)
this.$('a').click(this.testFunction);
}
关于javascript - 主干事件委托(delegate) eventName 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8687058/