[英]Calling a method from inside a view without using “this” keyword?
我的主干代码似乎有很多this.methodCall()
类型的调用,我很希望能够删除this
,而直接从View内部调用methodCall()
。
请参见以下代码:
app.Main = Backbone.View.extend({
el: '#main-div',
// how do I call this function without invoking "this"?
setPageCookies: function () {
console.log('setting page cookies called!');
},
initialize: function () {
// saw this online as a possible solution, but only seems to affect the scope of "this"
_.bindAll(this, 'setPageCookies');
// this works:
this.setPageCookies();
// HOWEVER, I'd like to be able to call it like this instead:
setPageCookies();
}
});
首先this.setPageCookies()
和setPageCookies()
具有截然不同的含义。
实现调用方式setPageCookies()
没有this
将是使setPageCookies
函数声明:
function setPageCookies() {
}
Backbone.View.extend({
setPageCookies: setPageCookies,
initialize: function() {
setPageCookies()
}
});
但是,现在不能用this
代替setPageCookies
除非使用bind
,或者除非围绕setPageCookies: setPageCookies
编写了一个复杂的包装器setPageCookies: setPageCookies
,它使用this
值并将其作为第一个参数传递。 这让我问-为什么要实现这一目标?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.