Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

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);
    },
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top