Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access `this` from callback

Similar question was already asked here How do I trigger the success callback on a model.save()?, but still no answer how to trigger events from callbacks.

So here is success callback in my code, in which I want to call addOne event to render saved Comment. Everything works well except this.addOne(receivedItem); - I can't use this in callback to trigger this event. Everywhere else - I can.

How to solve this problem?

CommentsListView = Backbone.View.extend({
    ...
    addOne: function (item) {
        var commentView = new CommentView({
            model: item
        });
        this.$el.append(commentView.render().el);
    },
    addNewComment: function (event) {
        var item = {
            post_id: this.$('#post_id').val(),
            text: this.$('#text').val()
        };
        var commentItem = new CommentItem();
        commentItem.save({'model':item}, { 
            success: function(receivedItem, response) {
                this.addOne(receivedItem); // Uncaught TypeError: Object [object Window] has no method 'addOne'.
            }
        }, this);
    }
});
like image 460
Gediminas Avatar asked Jan 15 '23 15:01

Gediminas


1 Answers

That happens because the success callback has a different scope, and this does not point to your view.
To quickly solve this, just make a reference to this and use it instead:

var self = this;
commentItem.save({'model':item}, { 
    success: function(receivedItem, response) {
        self.addOne(receivedItem); // works
    }
});

or you can use underscore's bind method to bind a different context to a function :

success : _.bind(function(receivedItem, response) {
    this.addOne(receivedItem); 
}, this)
like image 70
gion_13 Avatar answered Jan 24 '23 17:01

gion_13