views:

54

answers:

1

Hi all, this is the weirdest thing. My code is below:

function menuSwipe(init){
    dojo.query('div.fill div.container div.menu div.group ul').forEach(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

+2  A: 

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);
});
Guffa
Eh? I'm not sure what this has to do with Darren's question (init mysteriously becoming undefined). I also don't know what problem your answer would address anyway, the closure around setTimeout's callback is created from forEach's callback...
Angiosperm