开发者

Javascript function variable all of a sudden becomes undefined?

this is the weirdest thing. My code is below:

function menuSwipe(init){
    dojo.query('div.fill div.container div.menu div.group ul').for开发者_开发技巧Each(function(item){
        dojo.fx.wipeOut({
            node: item,
            duration: 1
        }).play();
        dojo.query('li', item).forEach(function(childrenItem){
            if (dojo.hasClass(childrenItem, 'active')) 
                childrenItem.parentNode.className = 'items active';
        });
        if (item.className == 'items active') {

            dojo.query('div.category', item.parentNode).forEach(function(parentItem){
                setTimeout(function(){
                    menuOpen(parentItem, init);
                    doGrayscale(parentItem);
                }, 100);
            });
        }
    });
}

Basically init stays in memory until it goes in the if (item.className == 'items active') conditional. After that it becomes undefined. It is a boolean value that I am setting. As long as it is before if (item.className == 'items active') it will retain its value. I have no reason why its doing this. I have tried to do this.init = and setting it as var init = init. Does anyone know or is there some way I can retain its value all throughout the function? Its not the init naming, I have tried a different name and it still does the same thing.

Thanks, Darren


The problem is that the timeout is running after the function has completed, so the parentItem variable has gone out of scope when the timeout runs.

Create a local variable in that scope, so that a closure is created for the timeout function. That way each iteration has it's own variable:

dojo.query('div.category', item.parentNode).forEach(function(parentItem){
  var itemCopy = parentItem;
  window.setTimeout(function(){
    menuOpen(itemCopy, init);
    doGrayscale(itemCopy);
  }, 100);
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜