9

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.

1 Answer 1

16

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.

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

2 Comments

This documentation link might be a better first choice for reference (although MDN does say the same, to their credit).

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.