事件触发时 el 未定义



>我从一个视图触发一个事件,如下所示:

select: function () {
    // Shorthand for the application namespace
    var app = brickpile.app;
    // Trigger the selected event
    app.trigger('selected', this.model);
}

并绑定到另一个视图中的同一事件:

initialize: function () {
    // Shorthand for the application namespace
    var app = brickpile.app;
    // bind to the selected event
    app.bind('selected', this.selected);
},

在我的函数中,我得到了当前的实例 el 属性?

selected: function (model) {
    // find the input hidden located in this views el
    $(this.el)... // is undefined
},

我错过了什么?

我将引用Backbone常见问题解答来回答您的问题

绑定"这个"

也许最常见的JavaScript"陷阱"是,当你将函数作为回调传递时,它的此值已丢失。使用骨干,在处理事件和回调,你经常会发现依赖 _.bind 和 _.bindAll 很有用来自下划线.js。

将回调绑定到主干事件时,可以选择传递可选的第三个参数,用于指定将在以下情况下使用的 this。稍后调用回调。

尝试

app.bind('selected', this.selected, this);

_.bindAll(this, 'selected');
app.bind('selected', this.selected);

最新更新