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);
}
});
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With