0

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);
    }
}
2
  • It's because you're passing unique function objects when you add and remove. 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. Commented Jul 27, 2013 at 15:25
  • Something you may want to consider is that DOM elements are objects to which properties can be added. If all you're doing is storing a number, you could add it directly to the element. That way instead of creating a unique handler for each element, you can name and reuse the same one, and therefore have a reference to it when you want to remove it from an element. If the property you add to the element is my_index, then in the handler, you'd do array[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. Commented Jul 27, 2013 at 16:00

1 Answer 1

1

The reason is that creatHandler always returns a new function and not the same one you attached. You should store the handlers and fetch them when you want to remove them.

var handlers = [];
function createHandler(i) {
    if (!handlers[i]) {
        console.log('Created ' + i);
        handlers[i] = function () {
            alert(array[i][AGE]);
        };
    }
    return handlers[i];
}

You can see it in action too: http://jsfiddle.net/balintbako/TQxua/

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh I see. I think I know what you mean, would you mind providing an example with your answer just to make sure? Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.