Preventing JavaScript memory leaks with Dojo disconnect

One of the things with using event listeners in JavaScript is that it causes memory leaks. This causes the website performance to slow down after a while. A pretty good description of how and why these memory leaks happen is explained here.

In Dojo, attaching events to an element are done as below:

dojo.connect(dojo.byId('elementId'), 'onclick'/*or other events*/, scope/*context*/, function(event) {
   //do something when the event happens.
});

Eugene Lazutkin’s solution here on StackOverflow is perfect in my opinion. I’ve started using it in all the Dijit widgets I’ve been writing. I put this in the destroy() method of the widget.

dojo.forEach(handles, dojo.disconnect);
About these ads

2 thoughts on “Preventing JavaScript memory leaks with Dojo disconnect

  1. The most unsafe practice that would create a memory leak is to do

    document.getElementById(“x”).innerHTML=””;

    you would avoid memory leaks only if you remove all event listeners on all element inside the element to be removed . Does your code take care of just that element or all the elements inside this element!

    • I am not sure, the dojo.disconnect removes event handlers to the element you initially appended to, if the reference to the element is no longer available as a result of using innerHTML, then I dont think it would help. I guess the right way is to stick to using innerHTML to set text content only, and not for any other dom manipulation.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s