Christopher Masser
Christopher Masser

Reputation: 829

"Obect has no method" when calling other function from within callback function

I'm using backbone and I'm trying to set a callback as below:

app.myView = Backbone.View.extend({

     events : {
        'click #myButton' : 'onClick',
        },

    onClick : function(e) {
        var self = this;
        myModel.save(null, {
            success : self.successAction
        });
        return false;
    },

    successAction : function() {
        this.myOtherFunction();
    },

    myOtherFunction : function() {
        this.$el.hide();
    }

}); 

This is the error I get:

TypeError: Object [object global] has no method 'myOtherFunction' 

How can I call another function of the same class from within a callback function?

Also, I would like to ask, is it in general possible to pass parameters with the callback function? Like this:

myModel.save({
    "success" : successAction(param1, param2)
});

successAction : function(param1, param2) {
    this.myOtherFunction();
}

Upvotes: 0

Views: 77

Answers (1)

PSL
PSL

Reputation: 123739

It seems that when the function successAction is invoked it is invoked from the global scope, so the context points to global object inside the callback, you can use function.bind (with shim support for older browsers), try :

onClick : function(e) {
    var self = this;
    myModel.save({
        "success" : self.successAction.bind(self)
    });
    return false;
},

and to pass arguments you could use:

myModel.save({
    "success" :  self.successAction.bind(self, param1, param2)
});

Upvotes: 6

Related Questions