Search code examples
javascriptjqueryjquery-eventsidempotent

How to make jQuery `bind` or `on` event handlers idempotent


Is there a way that I can call $(selector).bind('click', handler) or $(selector).on('click', handler) multiple times such that the handler only gets attached once?

Right now, I have multiple AJAX handlers with different success callbacks, each of which re-renders a different set of elements on the page. Ideally I'd like to refactor the "reattach events" routine to a single function rather than a routine for all.

The only way I can think of to do this right now is to explicitly unbind, for example:

$(selector).off('click');
$(selector).on('click', handler);

Looking for a way to do something like that automatically.


Solution

  • A better approach is just to move the .on call to a container. If you have a container, the .on sticks around and is applied to any existing or new children matching your selector:

    $(container-selector).on("click", "element-selector", function(event){
    // do stuff
    });
    

    http://api.jquery.com/on/

    Cheers.