我想这是一个简单的问题。我是 js
新手,尤其是 Backbone.js
。
我想知道的是如何在 jquery 函数中引用我的函数。
getLanguages: function() {
...
return languages;
},
render: function() {
...
$("input[type='checkbox']").bind("change", function() {
// todo: getLanguages
});
}
我尝试通过 this
获取语言,但是,当然,在本例中我得到了 checkbox
。
编辑: 就是这么简单。非常感谢大家!!!
最佳答案
这是 Javascript 中的一个经典问题。您需要在回调中引用 this
,但 this
会更改所绑定(bind)的元素。一种廉价的方法:
render: function() {
var that = this;
$("input[type='checkbox']").bind("change", function() {
that.getLanguages();
});
}
that
将保持定义为定义 render
的 this
。
但是,您正在使用 Backbone,它有更合适的方法来处理这种情况。我不知道您的 Backbone.View
类的名称,但这里有一个 example adapted from the documentation :
var DocumentView = Backbone.View.extend({
events: {
"change input[type='checkbox']": "doSomething"
},
doSomething: function() {
this.getLanguages(); # uses the correct this
}
});
在 render
中调用 bind
不是 Backbone Way。主干 View 是为了处理事件委托(delegate)而无需传递this
。
关于javascript - jquery中如何从另一个函数调用父类的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23852305/