I am building HTML5 applications at Sencha. It is a great platform, take a look...

 

  Ted Patrick - Developer Relations @ Sencha


   Note: This is the personal blog of Ted Patrick. The opinions and statements voiced here are my own.



useWeakReferences:Boolean = false

DIGG IT!     Published Monday, September 15, 2008 at 8:42 PM .

This is the last argument in the addEventListener method and it just might be one of the most important. Whenever you subscribe to events you have the option to set useWeakReferences to false (the default) or to true (unfortunately not the default). What seems incredible to me is the fact that this is the last argument and that it defaults to false.

When useWeakReferences is false the following happens:

THE CLASS INSTANCE OF THE SUBSCRIBED METHOD WILL NOT GARBAGE COLLECT.
Even if the instance is destroyed by lightening and crushed by your car, it will remain alive stuck within the addEventListener inner workings til you unsubscribe to the listener. Worse is that you most likely lost the instance that you subscribed and that is required to use removeEventListener successfully. The instance will remain in memory and the method will keep getting called, uggghhhhhhh.

A better way...

When useWeakReferences is true the following happens:

THE CLASS INSTANCE OF THE SUBSCRIBED METHOD WILL GARBAGE COLLECT, AHHHHHHH.
Even if the instance is destroyed by lightening and crushed by your car, it will die and the method subscribed will never be called again.

Garbage collection is a very tricky business. The Flash Player VM is constantly looking for objects without a strong reference to them to collect. The real dilemma is that strong references are very easy to create.

All it takes is one:

var a = foo;

or

var b = foo.method; // yes closures come with an instance reference... :(

or

this.addEventListener( MouseEvent.CLICK , foo.method );

and foo will never garbage collect until 'a' and 'b' are removed as references and removeEventListener is called. With complex apps there can be a ton of events and you need to be super careful with references. References are the devil in the details.

I am knee deep in event code for BX and I am being extra careful to make sure that events are easier to work with. Be careful with references, they can make a real mess if you are not careful.

cheers,

Ted :)


Where to find me:

Ted on Twitter - @__ted__
Ted on Adobe Groups
Ted on LinkedIn
Ted on Facebook
Ted at Adobe

Latest

Lists

Links

Jobs

city, state, zip

Archives