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);