类似的问题已经在How do I trigger the success callback on a model.save()?中提出,但仍然没有答案如何从回调中触发事件。
这是我代码中的success
回调函数,我想在其中调用addOne
事件来呈现保存的Comment。除了this.addOne(receivedItem);
之外,其他地方都运行良好--我不能在回调函数中使用this
来触发此事件。其他地方--我都可以。
如何解决这个问题呢?
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);
}
});
2条答案
按热度按时间ohtdti5x1#
发生这种情况是因为success回调具有不同的作用域,并且
this
不指向您的视图。要快速解决此问题,只需引用
this
并使用它:或者可以使用underline
bind
方法将不同的上下文绑定到函数:toiithl62#
这可能是一个较晚的答案。但会帮助正在查找它的人。这是从settimeout回调访问“this”关键字