aw *_*rud 7 javascript backbone.js backbone-views
Backbone 0.9.0更新日志说:
视图的事件哈希现在还可以包含直接函数值以及现有视图方法的字符串名称.
当我尝试以下操作时失败,说该事件的值是undefined.
var BB = Backbone.View.extend({
'initialize': function() {
this.$el.html('<input type="button" value="Click me!" />');
jQuery('body').html(this.el);
},
'events': {
'click input[type="button"]': this.buttonClicked
},
'buttonClicked': function() {
alert('button clicked!');
}
});
window.b = new BB()
Run Code Online (Sandbox Code Playgroud)
我误解了这个新功能吗?有人可以解释它的工作方式与我的预期不同吗?也许这只是我在定义时的'this'的JavaScript语法/值.
我习惯做的方式仍然有效:
'events': {
'click input[type="button"]': 'buttonClicked'
},
Run Code Online (Sandbox Code Playgroud)
mu *_*ort 14
当JavaScript解析器到达时:
'events': {
'click input[type="button"]': this.buttonClicked
},
Run Code Online (Sandbox Code Playgroud)
this很可能window,不是BB你期望的实例.该window对象没有buttonClicked属性(至少在你的情况下不是这样)所以你真的这么说:
'events': {
'click input[type="button"]': undefined
},
Run Code Online (Sandbox Code Playgroud)
而且你的错误.
如果查看源代码delegateEvents,您将看到ChangeLog的含义:
delegateEvents: function(events) {
// ...
for (var key in events) {
var method = events[key];
if (!_.isFunction(method)) method = this[events[key]];
// ...
}
},
Run Code Online (Sandbox Code Playgroud)
那个_.isFunction电话就是你感兴趣的.这意味着你可以这样说:
events: {
'click input[type="button"]': function() { alert('pancakes!') },
'click button': some_function_that_is_in_scope
}
Run Code Online (Sandbox Code Playgroud)
因此,您可以在events查找表中放置已定义的函数(如果它们可以访问,或者作为函数文字,可以是它们的名称).
| 归档时间: |
|
| 查看次数: |
4646 次 |
| 最近记录: |