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.

Why I Hate Software Developers

Being a Software Developer I know how slow and counter productive developers get with time. Its not that we don’t get time to meet the deadline(although exceptions are always there), it is just our thought of thinking ourselves as highly efficient and over qualified.
We always hate testers since they put us back to work and make us clean up our own mess. But it is just their job to put developers on job and guide the software development on a right path. Sometimes I feel, it is the testers who put the developers on the right track.
But wait, sometimes even testers get lazy too. The code in alpha and pre releases gets their nod to be released but when the code is in production suddenly some tester would raise a finger on a very trivial issue that should have been found during the pre release stage.
This time I as a developer think how stupid and lazy the tester was for not to find this trivial bug, but eventually this thought comes back to me as a boomerang asking why on earth did the developer not notice such a blunder. At this time I feel serious identity crisis for myself.

 

The Dream:

There is a saying “Good developers write their own code, but the best developers utilize already written code“. Now having said that I must admit, almost every coder has a dream to right the code from scratch and never wants to manage and clean up someone’s mess.
Apparently very few lucky ones get that chance, rest of us have to cope up with the situation. The situation gets even worse when the code has already been changed by more than four or five different people. The person currently working on the code has to somehow understand and manage the coding styles and thinking of coders before him.
The best thing is that the current developer will surely manage to get the code working. This situation remains almost every time the developers change their jobs. There is a worst thing about this: no manager will let you get away with this silly argument, even though they themselves understand the situation very well.

 

What exactly did you do? This is just a minor change; This is a general question asked by several managers. The problem gets worse if the change is related to UI. The developer has to take care of several others elements nearby to move one simple button from left to right. In the outcome(from a user’s or manager’s perspective) it is just a re-positioning of a button, but it is the developer who knows the pain behind it.
Yes it is true that a good coding practice can reduce the amount of work, but don’t forget that the code has already been modified by several other developers who are not in the project any more, so the current person in the developer’s cap has to bear it.

 

Despite of all these things and situations we somehow learn to “MANAGE” and not to break any existing functionalities of the software. With time we get mature and acquire better skill sets to provide better solutions to problems and sometimes you get appreciations too for that. This little piece of appreciation helps developers a lot to again start thinking themselves as a better creatures, hence the cycle of fall and rise continues. We don’t get out of it and that’s why I hate software developers or more specifically myself.

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!

Two Dimensional Arrays in JavaScript

JavaScript does not provide any direct notion of creating multi dimensional arrays as provided by languages like, C and Java. But there are ways to solve this problem and create a multi dimensional array.
Below we are trying to create a two dimensional array. The idea is simple and can be applied to create arrays with more than two dimensions:

function init2DArray(
    var twoDArray;
    var cols = 10, rows = 15;
    var indexI;
    twoDArray = new Array(cols);
    for (indexI = 0; indexI < cols; indexI += 1) {
        twoDArray[indexI] = new Array(rows);
        for( indexJ = 0; indexJ < rows; indexJ += 1) {
            twoDArray[indexI][indexJ] = 0;
        }
    }
}

Now since we have got the 2D array, we may want to initialize it with something (may be with a default value).
Simply add the add the following code in the for loop after the first line:

for( indexJ = 0; indexJ < rows; indexJ += 1) {
    twoDArray[indexI][indexJ] = 0;
}

I have tried to make the code above error free but if anly problem persists, please post it in the comments. Also please feel free to suggest any optimization in the code.

Best Resources For Web Developers and Learners

As a Web Developer I have come across some of the best online resources(blogs and websites from very good developers and Organizations) for Self Learners and Enthusiasts about web development.
The list starts here:

1.) John Resig: You definitely don’t want to miss his book Secrets of the JS Ninja
http://ejohn.org/
http://ejohn.org/category/blog/

2.) MDN: Every thing for a web developer’s needs and demos(My personal favorite)
https://developer.mozilla.org/en-US/
https://developer.mozilla.org/ms/demos/tag/tech:html5

3.) Quirks Mode: Cross browser and compatibility issues
http://www.quirksmode.org/

4.) Ben Nadel: For Latest web technologies AngularJS
http://www.bennadel.com/

5.) Digital Inspiration: How to guides and Tutorials
http://www.labnol.org/

6.) Position-Absolute: Latest Web related technologies
http://www.position-absolute.com/

7.) Cango Js: Amazing Library for creating interactive 2D and 3D objects in HTML5 Canvas
http://www.arc.id.au/Canvas3DGraphics.html

8.) KineticJS: Another amazing framework/library for interactive Canvas objects
http://kineticjs.com/

9.) HTML5Test: Check you browser support for latest HTML5 features
    http://html5test.com/

There is something for everyone’s taste and interest in this list. Hope you all like it.