Below I have a small JavaScript file that is designed to create elements for each array in the array. All works fine, apart from the last function, removeEventListeners(). This function doesn't return any errors, but it simply doesn't remove the listener.
Really appreciate any help! Thanks.
var array = [["Bob", 17, 1], ["Alan", 16, 1], ["Dave", 19, 1], ["Terry", 5, 1], ["Janet", 23, 0]];
var elements = [];
var AGE = 1;
function createHandler(i) {
return function() {
// Upon clicking the element show an alert with the age of that element (taken from array)
alert(array[i][AGE]);
}
}
for (var i = 0; i < array.length; i++) {
elements[i] = document.createElement("div");
elements[i].addEventListener("click", createHandler(i), false);
}
// This function is where the problem lies - it doesn't remove the handlers
function removeEventListeners() {
for (var i = 0; i < elements.length; i++) {
elements[i].removeEventListener("click", createHandler(i), false);
}
}
addandremove. To remove a listener, you need to pass the same function object you passed when you added, which means you need to reference it somewhere.my_index, then in the handler, you'd doarray[this.my_index][AGE]. I wouldn't reference large amounts of data, or other elements, but small things like numbers aren't a big deal.