【问题标题】:Access `this` from callback从回调中访问 `this`
【发布时间】:2012-12-14 09:56:12
【问题描述】:

How do I trigger the success callback on a model.save()? 已经在这里提出了类似的问题,但仍然没有回答如何从回调中触发事件。

所以这是我的代码中的success 回调,我想在其中调用addOne 事件来呈现已保存的评论。除了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);
    }
});

【问题讨论】:

标签: javascript backbone.js scope callback


【解决方案1】:

这可能是一个迟到的答案。但会帮助正在寻找它的人。这是从 settimeout 回调访问 'this' 关键字

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

【讨论】:

    【解决方案2】:

    发生这种情况是因为成功回调具有不同的范围,并且this 没有指向您的视图。
    要快速解决这个问题,只需引用 this 并改用它:

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

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

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

    【讨论】:

    • 你真是个天才!有用!它对其他人有用 - 我花了几个小时来解决这个问题(我还不太擅长 javascript):)
    • @MdaG 你指的是下划线的bind 方法吗?
    • 不,我的意思是发送“this”作为附加参数如何使其工作?我在这里有一个知识空白,因为我已经看到它在其他代码中也使用过。
    • @MdaG 这就是下划线的绑定函数的作用。它有两个参数:一个函数和一个对象,并返回一个以指定对象为作用域的新函数。我类似于 es5 中的标准bind 函数方法:var getFoo = function (){return this.foo;}.bind({foo:'bar'})。您可能应该阅读文档以消除差距:)
    • @MdaG 很抱歉,我之前没听懂你在说什么。你是对的:model.save 只需要 2 个参数。我真的不记得第三个参数是如何或为什么进入该函数调用的(因为这个答案可以追溯到一段时间前)。这是不必要的和误导性的,我为此道歉。无论如何,问题是通过在self 变量中使用对this 的引用来保留上下文。也更新了答案。谢谢
    猜你喜欢
    • 2013-06-12
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 2021-12-30
    相关资源
    最近更新 更多