Continuing in my efforts to make my code stop leaking (fun!), I’ve been working on a popup handler I wrote recently (which I plan to post and share as soon as, you know, it doesn’t leak).
This popup handler accepts as it’s parameters (among other things) a group of items (links for example) that it should observe and, when clicked or moused over, draw a popup on the page. I use Moo.fx to fade the element in and out.

My object stores this fx object in the as a variable attached to the DOM element it effects:

var popDetailsList = Class.create();
popDetailsList.prototype = {

myPopupDiv.fadeIn = new fx.Opacity(….);
}

This lets me re-use the effect object, but, more importantly, check to see it’s state. If the user mouses over or out, the effect transitions over the duration of the effect (configurable, but typically around 250ms). The effect object has a effect.now variable that is a numerical value of the transition state (in the case of opacity, a numerical value between 0 and 1 that represents opacity). I need to reference this value to determine if the effect is in transition, or if the element is hidden or visible. Thus I can’t just create new instances of the fx object whenever I want to fade in and out; I need to keep it around, which is why I store it in my object.

The problem is that in the fx object it stores a reference to the DOM element itself:

this.el = $(el) //where el is either a DOM object or an id passed in

This creates a circular reference (DOM element -> fx object -> DOM elemen -> etc.) and therefor leaks.

Fixing this means either discarding the DOM element every time I create it (so it works in the scope of each function in my object, but can’t be kept around to determine any kind of state) or chaning the moo.fx library to store the id of the element rather than the element itself:

this.el = $(el).id;

Any further reference to this.el in the moo.fx library then needs to be wrapped in $(). The moo.fx library is very small (133 lines) and the expanded moo.fx.pack library is another 167 so this change isn’t that difficult to put in place.

This change fixes a lot of my memory leaks. I’ve posted this to the moo.fx forums to get thier input on my changes; perhaps they’ll be included in the library (though I doubt it; it requires that every fx element have an id which I bet they don’t want to do).