mootools variable scope

强颜欢笑 提交于 2019-12-12 06:16:34

问题


how to access outer function's argument 'parent' ??? please see comments in code !!
last edit : This question is misleading, my problem is caused by wrong input argument

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:


within an each loop:

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

another acceptable way is:

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

although, using .bind(this) should work too... http://www.jsfiddle.net/dimitar/fFy4J/ - so what is the problem?




回答2:


if i understood correctly, your problem is that you cant do li.inject(parent)

there's no reason why you can't access 'parent' since it's been passed as a parameter to the function renderData()

I've tried this 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));
    }
});

and it works fine... but i'm no really sure what's the problem on your code



来源:https://stackoverflow.com/questions/4792508/mootools-variable-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!