views:

42

answers:

4

Good day!

I noticed that in anonymous event handler this is referenced to global, not my class. I know that I can use outer referenced variables (because it creates closures), but how to get right this context?

Simple example:

_movieClipClassVariable = new MyCustomSpriteSubclass();     
_movieClipClassVariable.addEventListener(MouseEvent.CLICK, function(event:Event):void {
            trace(this); //gives 'global'
});                     

What about memory usage and garbage collection objects with anonymous handlers? Is declaring handlers as class method better?

A: 

Yes you should really declare a class to not end up in thin air.

The delegating technique you used there is mostly used in Javascript. As a flash developer I'd recommend naming the function and keeping it all together in a class.

As for the garbage collection, you'd need to removeEventListener with the exact same syntax than the addEvenListener in order to free it for garbage collection.

HTH

keyle
As far as I know that this is not impossible to remove anonymous event listeners (without a nasty hacks). So it seems to remove listeners I have to declare it as class method.
artvolk
A: 

Instead of adding the functions declaration right inside the Event listener, declare the method in your class.

class myTestClass
{
     private function listenForEvents():void
     {
          _movieClipClassVariable = new MyCustomSpriteSubclass();     
          _movieClipClassVariable.addEventListener(MouseEvent.CLICK, onClipClassClickHandler);
     }

     private function onClipClassClickHandler(event:MouseEvent):void
     {
          trace(this); // this is the instance of current "myTestClass"
     }
}
Adrian Pirvulescu
A: 

I think most of the time declaring a method inside the class is the better choice, (because you don't have to think about the scope, to remove listeners, to not getting accidentally garbage collected, ...) however there are cases where an anonymous function might be a concise and clear approach. It depends.

For instance:

public class XYZ extends Sprite {
    ...

    private function renderBtn() : void {     
        var btn : SomeButton = new SomeButton();   

        var ref : XYZ = this;  

        btn.addEventListener(MouseEvent.CLICK, function(event:Event):void {
           trace("XYZ instance: " + ref);
           btn.removeEventListener(MouseEvent.CLICK, arguments.callee);
           removeChild(btn);
           proceed();
        });    

        addChild(btn);
    }

    private function proceed() : void { 
        ...
maxmc