Tuesday, June 30, 2009

Using Anonymous functions as event listeners

I am working in ActionScript right now, but I think we can do something similar in C# as well.

I am not 100% sure this is a good trick, but it works. If anyone thinks of a reason why we should not do this, let me know.

Problem: ClassA wants to listen to some events of ClassB. That's very simple, we just subscribe to that event. Since we needed some local context, we decided to use anonymous method to listen. Once the event occurs, we would like to un-subscribe from the event. There are two reasons why we might want to unsubscribe.

1. We do not want to perform that task again - which will be very specific to what you are really trying to do.

2. We want all our objects to be garbage collected. Not unsubscribing from events is the surest way to introduce memory leaks.

Solution: Use a variable of type "Function".

1 var listener:Function = null
2 instanceOfB.addEventListener(Event.EventName,
3         listener = function()
4        {
5                //do whatever you need to
6                instanceOfB.removeEventListener(Event.EventName, listener)
7        }        
8 )

See lines 3 and 6.

In C#, if I remember C# correctly, you would need a variable of type "Delegate". And yes, ActionScript does depend on event "name" while managing events. I like the C# mechanism much better.

No comments: