Search code examples
javascriptbackbone.jsbootbox

Pass "this" to a bootbox callback with Backbone


I'm using Backbone and bootbox. This is my code inside a 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 );
    }

I'm getting this error:

Uncaught TypeError: Cannot call method 'set' of undefined

Is there a way to pass the reference from the view?


Solution

  • As is a dependency of you could use its _.bind feature:

    _.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.

    In your case this could look like this:

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