How to effectively attach eventListeners to DOM elements

Anonymous functions are great way to quickly get the job done, but can be a huge problem when used carelessly. It is especially when attaching eventListeners to DOM elements. Take the code below for example. Here we are attaching an eventListner to the element for the “click” event. Now, later lets say for some reason or requirement we need to remove this “click” listener.


var element = document.getElementById("my-id");
element.addEventListener("click", function() {
// handle event
});

After this point we don’t have any reference to this handler since we forgot to keep a reference to it hence we cannot call the removeEventListener on the element, and the function stays in the browse memory.

Now assume the same scenario with multiple elements. An appropriate example of it might be when a NxN grid of elements is created. Lets assume that the cells in the grid is being created dynamically and appended to the DOM. If these cells need to have some event handler we might end-up doing the following:


var newCell = getNewCell(); // function to create a new cell

newCell.addEventListenet("click", function() {
// handle code
});

This way we ended up creating NxN anonymous functions to which we don’t have references to, in case event listeners need to be removed. Even after the element does not exist in the DOM, it is the browser to decide when to remove these abandoned listeners from its memory. But as a programmer its our job to clean up the mess we created.

How to fix this:

A better approach to add eventListeners to DOM elements would be to have some kind of reference to them as below:


function myListener(event, target) {
// handle the event
}

var newCell = getNewCell();

newCell.addEventListener("click", myListener);

Now whenever needed, this listener can to removed from the element:


newCell.removeEventListener("click", myListener);

Sometimes, there is a requirement of firing en event listener only once (for example an init button to be clicked for initializing the application). In that case, the addEventListener method can accept an optional object parameter with a Boolean property “once” to tell the browser that this listener needs to be fired only once and after that the listener needs to be removed. So in such cases adding anonymous function as eventListeners can be considered fine (but not with multiple elements as we are still creating several anonymous functions which will sit there untill the event occurs for the first time).


myElement.removeListener("click", function() {}, {capture: false, once: true, passive: true});

So it is quite essential to take precautions when attaching anonymous functions as eventListeners especially with multiple elements.

Better use of Memoization JavaScript

Referring to the post Generating Unique Strings (Ids) in JavaScript where we looked at how to generate unique strings in JavaScript. Also I mentioned the performance and memory issues with the approach.

So, here we are going to look a much better use or application of Memoization, but we won’t be using it for generating unique strings. We will be looking at another issue and will try to find an efficient way to handle it.

We all know that accessing DOM elements is pretty much costly in terms of performance. Lets look at an example of such an issue.

    function someFunction() {
        var text = document.getElementById("some-id").innerHTML;
        return text;
    }

Now suppose the above function is executed several times(reason could be anything like, user clicks). Every time this function is executed, it traverses the DOM and then returns it, which makes it really inefficient.
Now, I hope we have the idea of how to solve problem. Exactly, we will simply access the element one time and store it in a cache rather than looking into the DOM again and again.
So, here is how to do it:

    function someFunction() {
        if(someFunction.cachedElement) {
            return someFunction.cachedElement.innerHTML;
        } else {
            var ele = document.getElementById("some-id");
            someFunction.cachedElement = ele;
            return ele.innerHTML;
        }
    }

This technique can be more efficient if we are looking for multiple elements for example by className of the elements. In that case, we just need to get all the elements only once and store them in an array. So next time when the function is called all the elements are returned from the cache rather than going through whole DOM.
Pretty fast haan, isn’t it!