【问题标题】:Pass "this" to a bootbox callback with Backbone使用 Backbone 将“this”传递给 bootbox 回调
【发布时间】:2013-07-17 14:24:08
【问题描述】:

我正在使用 Backbone 和 bootbox。 这是我在视图中的代码:

    confirm : function(result) {
        if (result === true) { 
            var that = this;
            this.model.set({completed: '1'}); // Exception here
            this.model.save(
                    null, {
                success: function (model, response) {
                    Backbone.history.navigate("index", true);
                },
                error: function(model, response) {
                    that.model.set({completed: '0'});
                    var responseObj = $.parseJSON(response.responseText);
                    bootbox.alert(responseObj.message);
                }
            });
        }
    },

    completeProcess : function(event) {
        event.preventDefault();
        this.model.set({completed: '1'});
        bootbox.confirm("Confirm?", this.confirm );
    }

我收到此错误:

未捕获的类型错误:无法调用未定义的方法“set”

有没有办法从视图中传递引用?

【问题讨论】:

  • 你看过_.bind吗?
  • @Jack _.bind 比标准Function.prototype.bind 的价值是多少?向后兼容?我没有看到其他任何东西。
  • @JustinMorgan 如果标准(或者更确切地说是 native)bind 可用,则下划线将使用它。

标签: javascript backbone.js bootbox


【解决方案1】:

由于 是 的依赖项,您可以使用它的_.bind 功能:

_.bind(function, object, [*arguments])

将函数绑定到对象,这意味着只要函数 调用时, this 的值将是对象。
可选地,通过 函数的参数以预填充它们,也称为部分 应用。

在您的情况下,这可能如下所示:

completeProcess : function(event) {
  event.preventDefault();
  this.model.set({completed: '1'});
  bootbox.confirm("Confirm?", _.bind(this.confirm, this));
}

【讨论】:

  • 一个问题:bootbox传递的原始参数“result”呢?我的意思是,它只是被忽略了吗?
  • 所以我试过了,但我仍然从确认而不是这个参考中得到结果。我两个都需要。
  • 对不起!明白了,明白了。非常感谢!
【解决方案2】:

或者,您可以执行以下操作来保留原始“this”:

var _this = this;

bootbox.confirm({
    message: Message ,
    callback: function(result) {
        console.log(this + " != " + _this);
    },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 2016-02-27
    • 2011-01-08
    相关资源
    最近更新 更多