2011-01-25 11 views
0

外部関数の引数 'parent'にアクセスする方法??? コード のコメントをご覧ください!
最後の編集:この質問は誤解を招く恐れがあり、私の問題が間違った入力引数の各ループ内mootools変数スコープ

renderData : function(parent, children){ 
      children.each(function(e, index){ 
       var li = new Element('li'); 
       var hasChildren = false; 
       if(e.children && e.children.length >0){ 
        var img = new Element('img'); 
        img.src = 'a1.png'; 
        img.inject(li); 
        hasChildren = true; 
       } 
       if(e.icon){ 
        var img = new Element('img'); 
        img.src = e.icon; 
        img.inject(li); 
       }else{ 
        var img = new Element('img'); 
        img.src = 'b1.png'; 
        img.inject(li); 
       } 
       li.set('html',e.text); 
       console.log(this); 
        // how to access outer function's argument 'parent' ??? 
       li.inject(parent); 
       if(hasChildren){ 
        var ul = new Element('ul'); 
        this.renderData(ul, e.childRen); 
        ul.inject(e); 
       } 
      }.bind(this)); 

答えて

1

によって引き起こされる:

array.each(function(el) { 
    this.method(); // this == (instance/scope) 
}, this); // where **this** is your parent scope. 

別の許容可能な方法は次のとおりです。

var self = this; 
... 
array.each(function(el) { 
    self.method(); // fine. 
}); // where this is your parent scope. 

http://mootools.net/docs/core/Types/Array#Array:Array-each

でも、.bind(this)を使用すると... http://www.jsfiddle.net/dimitar/fFy4J/ - 何が問題なのですか?

1

私が正しく理解している場合、あなたの問題はあなたが私は「それがrenderData()

関数にパラメータとして渡されていますので、あなたが「親」にアクセスできない理由はありませんli.inject(parent)

を行う傾けることですこのsimple test

var test; 
window.addEvent('domready', function(){ 
     test = new TestClass(); 
}); 

var TestClass = new Class({ 
    Implements: [Options, Events], 
    initialize: function(){ 
     this.renderData($('parent'),$$('span')) 
    }, 

    renderData : function(parent, children){ 
      children.each(function(e, index){ 
       console.log(parent); 
      }.bind(this)); 
    } 
}); 

を試してみましたが、それが正常に動作します...しかし、私はあなたのコードに問題が何何本当に確信しているんVEの

+0

別の問題が原因で申し訳ありません。 – kuangfuking