I asked this earlier, got linked to This Thread which didn't really help me what so ever.
I have got a list of instances of a class, these classes store reference to an DOM element, and a method, and an INT.
I need to go through each of these class instances and assign the method to the click event of the elements.
for(var i = 0, l=children.length; i<l; i++) {
var child = children[i];
if(child.nodeType === 1 && child.tagName === "LI") {
listItems[x] = new subMenu(child);
child.addEventListener('click', function(x) {
listItems[x].toggle(); <!------- x is always 7, it should be 0-6
}, false);
x++;
}
}
Below is the class:
class subMenu {
constructor(obj) {
this.elm = obj;
this.state = 0;
}
toggle() {
if (this.state === 0) {
addClass(this.elm, 'toggled');
this.state = 1;
} else {
removeClass(this.elm, 'toggled');
this.state = 0;
}
}
}
Here is an image of the listItems
:
Edit: If I make the changes I believe to be correct from the linked post, I get this:
var menuParent = document.getElementById('megamenu');
var children = menuParent.childNodes;
var x = 0;
for(var i = 0, l=children.length; i<l; i++) {
var child = children[i];
if(child.nodeType === 1 && child.tagName === "LI") {
listItems[x] = new subMenu(child);
child.addEventListener('click', bindToggle(x), false);
x++;
}
}
function bindToggle(i) {
return listItems[i].toggle();
}
}, false);
However the toggle()
method is simply running once on assignment and then not running again when I click the element.
Edit 2 Sorry i did actually do it correct the first time, just got the code wrong above. So i have amended my code to return a function to the EventHandler.
var menuParent = document.getElementById('megamenu');
var children = menuParent.childNodes;
var x = 0;
for(var i = 0, l=children.length; i<l; i++) {
var child = children[i];
if(child.nodeType === 1 && child.tagName === "LI") {
listItems[x] = new subMenu(child);
child.addEventListener('click', bindToggle(x), false);
x++;
}
}
function bindToggle(x) {
return function() { console.log("Value: " + x); }; // listItems[x].toggle();
}
However the console.log
is simply outputting
Value: 2
If I add a console.log(x)
the line above the EventHandler` then it displays 0-6 like it should, so the value im passing over to the function shouldn't be the issue.