你如何从使用backbone.js的javascript闭包中调用其他内部方法?

时间:2012-04-25 19:43:15

标签: javascript backbone.js closures

以下是我展示问题的示例对象。

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();

2 个答案:

答案 0 :(得分:1)

旧的“自我”技巧......引用它,称之为自我,并在函数中引用它。

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();
}

答案 1 :(得分:1)

由于您使用的是Backbone,因此您也可以使用Underscore的绑定功能。定义callClosure后,可以使用适当的绑定包装它:

callClosure = _.bind(callClosure, this);