[Dojo-interest] Closures and memory usage (was: Widgets and memory issues)

Ed ednotover at gmail.com
Mon Feb 5 14:52:37 MST 2007

> From: Robert Coup <robert.coup at onetrackmind.co.nz>

Another option is to do something like this:
> function setupStuff(elements, handlerMessage) {
>     var handler = function() {
>        alert(handlerMessage);
>     }
>     var eLen = elements.length
>     for (var ii=0; ii<eLen; ii++) {
>        dojo.event.connect(elements[ii], "onclick", handler);
>     }
> }
> The handler function is therefore local in scope to setupStuff, but also
> has the benefits of being a closure (ie. it can access handlerMessage).

From: "Karl Tiedt" <ktiedt at gmail.com>

> Except in this case I believe:
>    for (var ii=0; ii<eLen; ii++) {
>       dojo.event.connect(elements[ii], "onclick", handler);
>    }
> Will connect all your events to elements[elements.length-1] due to lack of
> closure there ;)
> I think anyways from my experience that that would be the case. hehe

I thought about this for a while, and I don't follow the logic.  So I coded
it up and it works as Rob describes (and as I expected), where the handler
function is connected to each element in the elements array.

I certainly follow that if we were redefining the handler function within
the loop, then we'd have each element tied to the final handler definition -
the final function definition will be the retained closure.  Is that what
you meant, or am I missing something fundamental here?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://dojotoolkit.org/pipermail/dojo-interest/attachments/20070205/09ef34c8/attachment.html

More information about the Dojo-interest mailing list