Is it Always Better to Create Event Handlers In Their Own Method Instead of Inline? [closed]

StackOverflow https://stackoverflow.com/questions/21125474

  •  28-09-2022
  •  | 
  •  

Question

Which approach is better and why? If it's not so black and white, what instance calls for which approach?

function bindStuff() {
    var myElement = document.getElementById('someElement');

    myElement.addEventListener('click', function(e) {
        // do stuff
    });
}

Or

function clickHandler(e) {
    // do stuff
}

function bindStuff() {
    var myElement = document.getElementById('someElement');

    myElement.addEventListener('click', clickHandler);
}
Was it helpful?

Solution

There is a case where named handlers are prefered.

Suppose you bind an handler to an element; for some reason that element must be removed. You remove it; what about the binding DOM element/handler?

This situation leads to memory leaks. Besides expect some flaws in case you bind the same handler to an element that mimic the one you previously removed.

Whenever you need to remove DOM elements against which handlers have been bound to, use a named handler because you need to pass the handler when unbinding the DOM and the handler.

So the counterpart to addEventListener is removeEventListener

OTHER TIPS

If it's something extremely small, it's fine to inline them, but it's more difficult to read the code if you're doing more than one thing.

There's no 100% correct answer, but generally if it's one statement, it's ok to inline it, whereas multiple statements should go in their own methods.

You should generally prefer whichever style you feel is easiest to read and maintain. However, the second option does have one downside: it pollutes the global namespace.

I actually prefer a third option:

function bindStuff() {
    var myElement = document.getElementById('someElement');

    var clickHandler = function(e) {
        // do stuff
    }

    myElement.addEventListener('click', clickHandler);
}

But again, this is mostly a matter of preference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top