开发者

Backbone problem with this object

开发者 https://www.devze.com 2023-04-08 04:05 出处:网络
This is my View in Backbone framework: jQuery(document)ready(function() { com.company.View = Backbone.View.extend({

This is my View in Backbone framework:

jQuery(document)ready(function() { 

com.company.View = Backbone.View.extend({
  initialize : function() {
     myCollection.bind('add', this.onSuccess);
  },

  onSuccess : function(model) {
    // do something
    this.somethingElse();
  },

  somethingElse : function() {
    // do something else
  }
});

});

Now the problem is inside onSuccess function the this object doesn't belong to the View anymore, it belongs to model. So, when I call this.som开发者_C百科ethingElse() I got undefined.

How can I successfully call this.somethingElse inside onSuccess?


You want to bind your function to the context of the View object.

In initialize, do this:

initialize : function() {
    _.bindAll(this, "onSuccess");
    myCollection.bind('add', this.onSuccess);
}


The problem is you're relying on this to point to the original object. Unlike many languages this in Javascript changes based on the manner in which a method is called. Often in a callback it's invoked with this pointing to a different object or simply none at all (undefined).

One way to work around this is to remove the reliance on this in favor of a function local variable which can't be interferred with. For example

com.company.View = Backbone.View.extend(
   return function() {
      var self = {}
      self.initialize = function() {
        myCollection.bind('add', self.onSuccess);
      };
      self.onSuccess = function(model) {
        // do something
        self.somethingElse();
      };
      self.somethingElse = function() {
        // do something else
      };
      return self;
    }();
});
0

精彩评论

暂无评论...
验证码 换一张
取 消