backbone.js 从回呼存取'this'

shyt4zoc  于 2022-11-10  发布在  其他
关注(0)|答案(2)|浏览(203)

类似的问题已经在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);
    }
});
ohtdti5x

ohtdti5x1#

发生这种情况是因为success回调具有不同的作用域,并且this不指向您的视图。
要快速解决此问题,只需引用this并使用它:

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

或者可以使用underline bind方法将不同的上下文绑定到函数:

success : _.bind(function(receivedItem, response) {
    this.addOne(receivedItem); 
}, this)
toiithl6

toiithl62#

这可能是一个较晚的答案。但会帮助正在查找它的人。这是从settimeout回调访问“this”关键字

CommentsListView = Backbone.View.extend({
...
    addOne: function (item) {
        // DO Stuff
    },
    addNewComment: _.bind(function (event) {
        setTimeout(_.bind(function(){ 
            this.addOne(/*receivedItem*/);
        }, this), 1000);
    }, this)
});

相关问题