![](/img/trans.png)
[英]Backbone.js: How do you call a View's “method” from outside the View's scope (e.g: inside a model's validation handler)
[英]How do you call other internal methods from inside a javascript closure with backbone.js?
这是我演示该问题的示例对象。
Dog = Backbone.Model.extend({
initialize: function () {
},
Speak: function (sayThis) {
console.log(sayThis);
},
CallInternalSpeak: function () {
this.Speak("arf! from internal function.");
},
CallSpeakFromClosure: function () {
this.Speak("arf! fron outside closure.");
var callClosure = function () { // think of this closure like calling jquery .ajax and trying to call .Speak in your success: closure
console.log("we get inside here fine");
this.Speak("say hi fron inside closure."); // THIS DOES NOT WORK
}
callClosure();
}
});
var rover = new Dog;
rover.Speak("arf! from externally called function");
rover.CallInternalSpeak();
rover.CallSpeakFromClosure();
旧的“自我”技巧......引用它,称之为自我,并在函数中引用它。
CallSpeakFromClosure: function () {
this.Speak("arf! fron outside closure.");
var self = this;
var callClosure = function () {
console.log("we get inside here fine");
self.Speak("say hi fron inside closure."); // THIS DOES NOT WORK
}
callClosure();
}
由于您使用的是Backbone,因此您也可以使用Underscore的绑定功能。 定义callClosure后,可以使用适当的绑定对其进行包装:
callClosure = _.bind(callClosure, this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.