PDA

View Full Version : Event.currentTarget ?



endemoniada
September 6th, 2007, 01:18 PM
Hi guys,

Am I doing this properly:



var myTimer:Timer=new Timer(100,10);
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE ,timerComplete);
myTimer.start();

public function timerComplete(event:TimerEvent) : void {
// clean up the listener
event.currentTarget.removeEventListener(TimerEvent .TIMER_COMPLETE,timerComplete);
}


Should I be using currentTarget like that ?

Thanks.

cesig
September 6th, 2007, 01:31 PM
That seems a little odd to me. I'm not an expert on garbage collection, but if you set the listener to a weak reference when you set it, you won't have to explicitly delete it, so long as the object that you're listening to no longer exists.

If you're not deleting the timer once it's complete, then I might suggest just referencing timer directly. Unless you're planning to use 'timerComplete' for multiple timers.

Otherwise, if it works, then I don't see a problem with it. Though I've never seen that done before.

Maybe someone with more experience with this can weigh in and clarify.

endemoniada
September 6th, 2007, 05:02 PM
Hi,

The reason I'm doing it that way is because the Timer object isn't a class member, it's scope is local to the function it's created in and that's the only way I can access it. Maybe that's a bad way to do it ? I come from C(++) so this garbage colection stuff is confusing.

Thanks.

cesig
September 6th, 2007, 06:01 PM
Well like I said, it's unconventional. But I can't think of another way to do it in this situation.

If you want to read more about GC, Grant Skinner has a great series of articles about it (http://www.gskinner.com/blog/archives/2006/06/as3_resource_ma.html).

soulwire
September 6th, 2007, 07:10 PM
The thing about the GC is that even specifically telling it to remove a listener wont cause it to delete it from memory immediately, it will just mark it for when it does its next sweep. So there's nothing wrong with your method, but as Cesig says, a weak refference could also work (though I read on this forum someone had problems with timers and GC deleting before the function was executed! Not sure about that though).

Your method is good because it will remove listeners from any target that has registered for your onComplete event, which makes it nicely reusable.