I came to AS3 from the JS world, and I have to admit that anonymous functions are my weakness. I use them everywhere. Now, when I came to AS3, I heard and read in many places that AS and Flash do extremely poor garbage handling, so you need to clean, delete, and delete all event handlers and event objects manually to avoid strange and inexplicable memory leaks and crashes. Not sure how much of this is true, but I would like to follow best practices from the start.
So my question is: how bad is the idea of ββusing anonymous functions as event handlers? Consider, for example, the following code:
addEventListener(Event.ENTER_FRAME, function() : void { controls.elapsed = stream.time; });
contorls.elapsed is a setter that, in addition to setting the current playback time for the video player, updates the entire user interface, and the stream is a NetStream object that transmits the current video.
There are many other places where an anonymous function can make the code more understandable and understandable. Check the following code for a simple fade effect for the control panel:
public function showControls() : void { var self:Controls = this; if (!visible) { visible = true; fadeTimer = new Timer(30, 10); fadeTimer.addEventListener(TimerEvent.TIMER, function() : void { self.alpha += 0.1; }); fadeTimer.addEventListener(TimerEvent.TIMER_COMPLETE, function() : void { self.alpha = 1; }); fadeTimer.start(); } }
I like the way it looks and fits into the code, but I'm worried about leaks. Although the Event.ENTER_FRAME handler will probably never become harmful in this form, what about timer listeners. Should I remove these listeners manually or will they be deleted automatically as soon as I set fadeTimer = null ? Is it even possible to remove listeners with anonymous functions?
event-handling anonymous-function actionscript-3
jayarjo
source share