Search code examples
javascriptbackbone.js

Backbone: Correct way of passing 'this' reference to anon functions in success/error callbacks


Given the backbone view function below, what is the correct way of passing this (i.e. the current view) to the anonymous function defined in the callbacks?

addSomething: function(e) {
    var newSomething= this.model.somethings.create({
        someProperty: xxx
    }, {
        success: function(m, response) {
            this.doSomething(); //***HERE****
        },
        error: function(m, response) {
            //Error
        }
    });
},

Without and changes, the this in the anon function is set to the window.

I can a set a reference like this:

var thisView = this;

and then just refer to thisView instead of this in the anon function, but this doesn't seem very elegant. Is there a better way?


Solution

  • In order to better organize my code and work around this problem, I never put success and error callbacks directly in-line with my calls. I always split them out to their own functions. This let's me keep the code clean and also use the _.bindAll method to ensure I have the correct context for this.

    SomeView = Backbone.View.extend({
      initialize: function(){
        _.bindAll(this, "createSuccess", "createError");
      },
    
      addSomething: function(e) {
        var newSomething= this.model.somethings.create({someProperty: xxx}, {
          success: this.createSuccess,
          error: this.createError
        });
      },
    
      createSuccess: function(m, response) {
        this.doSomething();
      },
    
      createError: function(m, response) {
        //Error
      }
    });