开发者

Question regarding "this" inside anonymous function of prototype.js .each method

开发者 https://www.devze.com 2023-04-05 05:50 出处:网络
I\'ve been searching for hours for a solution to this problem. I\'m creating a table using prototype.js 1.6.0.1 and am having trouble with the this object in context with the .each function. here is a

I've been searching for hours for a solution to this problem. I'm creating a table using prototype.js 1.6.0.1 and am having trouble with the this object in context with the .each function. here is a snippit.

var Table = Class.create({
  initialize : function(id) {
    this.elmnt = $(id);
    this.rows = [];
  },
  initRows : function() {
    $A(this._elmnt.tBodies).each(function(body) {
      $A(body.rows).each(function(row) {
        //right here is where i would like to call
        // this.rows.push(row);
        console.log(this); // prints DOMWindow
      });
    });
  }
});

As you can see inside the secon开发者_Python百科d .each function this resolves to DOMWindow. I would like to be able to call this.rows.push(row) but I can't as "this" isn't resolving as expected.

Any help would be appreciated. I know i could do the standard (i=0; i < length; i++) loop but I was trying to make this a little cleaner. Thanks for any guidance you can offer.


The easiest way to work around this is to save this at the start of initRows and refer to in within the each functions

initRows : function() {
    var self = this;
    $A(this._elmnt.tBodies).each(function(body) {
      $A(body.rows).each(function(row) {
        //right here is where i would like to call
        self.rows.push(row);
        console.log(self); // prints DOMWindow
      });
    });
  }

The problem you're running into is that this can be manipulated by the caller of the function. It's very common in callbacks to set this to an element which is relevant to the call back. In the case of each it's set to the element for the current iteration of the value.

The self trick works because it saves the this as it's bound in the function initRows and then uses that saved value in the iteration.


initRows : function() {
    $A(this._elmnt.tBodies).each(function(body) {
        $A(body.rows).each((function(e, row) {
            e.rows.push(row);
            console.log(e);
        }).bindAsEventListener(this, row));
    });
}
0

精彩评论

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

关注公众号