4

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?

dierre
  • 7,140
  • 12
  • 75
  • 120

2 Answers2

3

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));
}
jantimon
  • 36,840
  • 23
  • 122
  • 185
  • a question: what about the original parameter "result" passed by bootbox? I mean, is it just ignored? – dierre Jul 17 '13 at 16:20
  • so I tried it but I'm still getting the result from the confirm and not the this reference. I need both. – dierre Jul 17 '13 at 20:12
0

Alternatively, you could do something like this to hang on to the original 'this':

var _this = this;

bootbox.confirm({
    message: Message ,
    callback: function(result) {
        console.log(this + " != " + _this);
    },
oskare
  • 1,061
  • 13
  • 24