Frage

I'm using the code from this answer https://stackoverflow.com/a/18055789/3250077 for a project.

In this fiddle http://jsfiddle.net/UpuDU/ on line 12 there is a off method

faqTab.off('click').on('click', function()

I'm new to programming and I read that it removes event handlers, but when I delete that part of the code, like this

faqTab.on('click', function()

nothing appears to change. What is happening inside the code? Is this really necesary or is just a "good practice". Not using this can lead to problems in more complex code?

War es hilfreich?

Lösung

If you don't remove an event handler before you add a new handler you can end up with the same method being called multiple times for the same event. So the answer to whether or not this makes a difference really depends on how often this code is run. As a general rule it isn't a bad practice to remove the existing handlers before adding a new handler.

Take the following example. In this example you would have an issue if this click function was called either directly or indirectly from the button being clicked:

var clickFunction = function () {
    // add the event AGAIN: BAD!
    $("#test-button").on("click", clickFunction);
};

See this in a JSFiddle: http://jsfiddle.net/4Qv8T/1/

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top