【发布时间】:2014-02-25 14:33:11
【问题描述】:
我正在使用关于我在另一个类中评估的页脚的自定义选项扩展主干视图。
看起来像:
var EditUserView = Backbone.View.extend({
footer: {
name: "Hello",
label: function() {
//Return "Create" if it's a new model without id, or else "Save"
return this.model.id ? "Save" : "Create";
}
}
});
如您所见,属性应该能够定义为返回字符串或普通字符串值的函数。 我使用 _.result 在 FooterView 中评估这些选项:
initialize: function(options) {
//"options" is the footer-object from the view.
this.data = {
name: _.result(options, "name"),
label: _.result(options, "label")
};
}
但问题是我无法在上面定义的标签函数中访问 EditUserView 的 this。我也无法定义var that = this,因为我在扩展对象时没有放置局部变量的位置。
如何使我在 footer-object 中定义的函数具有 UserEditView 的 this-scope?
我也可以:
footer: {
name: "Hello",
label: this.getName
},
getName: function() {
return this.model.id? "Save":"Create";
}
如果其他方式不可行或者这种方式更容易做到。
【问题讨论】:
-
你可以使用 .bind(this) 吗?
-
如果您在我的示例中告诉我在哪里调用它,我认为没有理由不这样做。
标签: javascript backbone.js scope this