简体   繁体   中英

How to make sure that click handler is only registered once?

I have this piece of code:

function expandCollapse(hypId, ElemId, ShowText, HideText) {
    var handler = function () {
        $("#" + ElemId).toggle();
        toggle(hypId, ElemId, ShowText, HideText);
    }

    $('#' + hypId).live('click', handler);

}

I want to make sure that no matter if this code is called for >1 time, it shouldn't do anything as long as the same hypId is being registered for click event. How do I do that?

A couple things:

1: You shouldn't be using live() , it's deprecated .

2: The easiest way to handle this kind of situation (if the element is around when you do the expand/collapse) is to use namespacing. So like this:

function expandCollapse(hypId, ElemId, ShowText, HideText) {
    var handler = function () {
        $("#" + ElemId).toggle();
        toggle(hypId, ElemId, ShowText, HideText);
    }

    $('#' + hypId).off('click.mynamespace').on('click.mynamespace', handler);
}

Replace mynamespace with something of your choosing that's relevant to the handler in question. That way, it will remove any existing handlers that it might have attached before re-adding the handler with the new options without impacting any other handlers that might be in place.

$('#' + hypId).one('click', handler);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM