Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary/advisable to check if an eventHandler exists before trying to remove it?

I've got something like this:

if (something) {
    init();
} else {
    document.addEventListener('CUSTOM_EVENT', init, false);
}

var init = function() {
    document.removeEventListener('CUSTOM_EVENT', init, false);
    // do stuff
}

Do I need to add some kind of check around that removeEventListener call? If so, I could do:

var eventAdded = false;
if (something) {
    init();
} else {
    document.addEventListener('CUSTOM_EVENT', init, false);
    eventAdded = true;
}

var init = function() {
    if (eventAdded) {
        document.removeEventListener('CUSTOM_EVENT', init, false);
    }
    // do stuff
}

but that feels a bit inelegant. I'd rather just leave the raw removeEventListener call if that's no big deal, or do something that doesn't require having an external var if possible.

like image 497
sprugman Avatar asked Mar 28 '12 16:03

sprugman


1 Answers

https://developer.mozilla.org/en/DOM/element.removeEventListener

Calling removeEventListener() with arguments which do not identify any currently registered EventListener on the EventTarget has no effect.

like image 87
James McLaughlin Avatar answered Sep 23 '22 21:09

James McLaughlin