javascript - 使用 Backbone 将 "this"传递给引导框回调

标签 javascript backbone.js bootbox

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

    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 );
    }

我收到这个错误:

Uncaught TypeError: Cannot call method 'set' of undefined

有没有办法从 View 传递引用?

最佳答案

作为 的依赖项你可以使用它的 _.bind 功能:

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

Bind a function to an object, meaning that whenever the function is called, the value of this will be the object.
Optionally, pass arguments to the function to pre-fill them, also known as partial application.

在您的情况下,这可能看起来像这样:

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

关于javascript - 使用 Backbone 将 "this"传递给引导框回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17702422/

相关文章:

Backbone.js 错误 - 未捕获的 TypeError : Object [object Object] has no method 'set'

javascript - Bootbox meteor 形式: preventing blank submissions

bootbox - 关闭对话框或关闭时回调

javascript - 为元素的事件设置名称

javascript - JQuery 功能列表滑动延迟

javascript - Marionette Collection View 多个dom追加

node.js - Backbone、Node 和 Mongo 错误验证和通信

javascript - Bootbox:关闭对话框/点击 'X'按钮后的回调函数

javascript - 将 li 元素移动到列表顶部

javascript - 在 Javascript/Jquery 中传递查询字符串