views:

419

answers:

1

Some code I am working with replaces some HTML elements that have Dojo event listeners with new HTML coming from an AJAX call (using .innerHTML=). I have read that event listeners should be disconnected using the dojo.disconnect(handle) method before they are replaced to prevent memory leaks.

Is it possible to derive all handles connected to a particular element, so that I can pass each one to .disconnect(handle), or is it up to me to maintain this list in my code?

+2  A: 

Actually if you are using widgets they normally should disconnect stuff in tehir destroy() method. If you are handling the nodes yourself, I see two ways you can go.

1) Manage all connects manually, means storing them somewhere. 2) Probably the safer one: store all the connect handlers in the node they connect to, like so:

node._connectHandlers = [];
node._connectHandlers.push(dojo.connect(node, "onclick", ...));

And later you can simply disconnect them all using

dojo.query("*", nodeContainingConnects).forEach(function(node){
    if (typeof node._connectHandlers!="undefined"){
        dojo.forEach(node._connectHandlers, "dojo.disconnect(item)");
    }
});

Actually, this may work well, but there might be a more efficient way to get all connects by nodes. I just didnt find it. hth

Wolfram Kriesing
thanks, I'll try it out!
tehblanx
Since I don't expect my AJAX-populated region to contain more than a handful of event-handlers, I ended up storing all of the handles for all of the nodes in one array in my dojo module. I can pass each element to the disconnect method without having to iterate over any of the nodes on my page. There does seem to be an effect on how much memory FireFox is using as I trigger AJAX calls. Thanks again for your help!
tehblanx