I have a variable id that is generate in a for loop. For some reason, the id changes from 0 to 1 when it is passed in a callback. My guess is that I am passing the id parameter incorrectly.
refreshMenu: function(mods, callback){
var menu = document.getElementById('menu'),
ul = document.createElement('ul');
menu.innerHTML = '';
menu.appendChild(ul);
for(var id = 0; id < mods.length; id++){
var li = document.createElement('li'),
that = this;
ul.appendChild(li);
li.setAttribute('id', id);
li.innerHTML = mods[id].get('name');
console.log(id); // HERE ---> 0
li.addEventListener('click', function(){
that.selectMenu(li, function(){
console.log(id); HERE ---> //1 ?
that.selectList(id - 1);
});
}, false);
}
callback();
},
selectList: function(id)
var activeList = this.activeList();
console.log(id);
if (activeList.id == id){
return;
}
else if (activeList){
activeList.setAttribute('class', '');
};
var target = document.getElementById(id);
target.setAttribute('class', 'activeList');
},
selectMenu: function(li, callback){
if(li.className == 'activeMenu')
return;
var active = document.getElementsByClassName('activeMenu')[0];
if(active)
active.setAttribute('class', '');
li.setAttribute('class', 'activeMenu');
callback();
},
It’s a very common gotcha when building closures within for loops. All of the functions you’re creating refer to the same id variable, and the for loop mutates the variable.
One simple way to fix this: make a helper function that creates these functions, and have the helper take its own parameter.
The helper’s binding of its id argument shadows that of the for loop, and this is a good thing! We’re intentionally doing this. We also capture li, since it too needs to be held.
Later, we call makeClickFunction, passing in the current value within the for loop. for will continue to mutate its id, but that’s ok: that mutation has no relationship to the behavior on makeClickFunction‘s closures.