user
user

Reputation: 165

AS3 - Uses of addEventListener arguments

Now I am working on Flex 4 with AS3. In most of time I am using the addEventListener. This listener default arguments are type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false. But most of the developers doesn't consider the last 3 arguments. But I want to know the uses of these 3 arguments?

Anyone call tell me answer?

Upvotes: 2

Views: 1133

Answers (1)

Creative Magic
Creative Magic

Reputation: 3141

Most of the times those three last parameters aren't necessary, because it's usually better to use a programming pattern to manage dependencies rather than leaving it to hard-to-debug spaghetti code that goes through many other classes.

Yet, there is a purpose for them and they can come in very handy:

  • useCapture - To register a listener with an event target’s ancestor for the capture phase of an event dispatch, we set addEventListener( )’s third parameter, useCapture, to true, as in:

    theAncestor.addEventListener(myEvent, MyListener, true);

    The code causes MyListener( ) to be executed whenever AS3 dispatches myEvent targeted at one of theAncestor’s descendants before that descendant receives notification of the event.

  • priority - if you add more than one event listener to an object, the one that has higher priority will be triggered first. If you add two or more listeners with same priority, the one that was added first will trigger first. Just imagine that upon creating an object you've added an event listener, but later on you need to add another one and you want that new one to run first. Registering it with higher priority should do the trick.

  • weakReference - this is not a commonly used one, because Flash's garbage collector can run any time or even never. The problem is that regardless of any use of weak references, an object may continue to dispatch and listen to events until it gets garbage collected.

    By default, an object that registers a listener for a given event maintains a reference to that listener until it is explicitly unregistered for that event—even when no other references to the listener remain in the program.

    By setting the value to true the object will lose the reference to the listener when the object is eligible for garbage collection.

    It's used to prevent memory leaks, but useWeakReference only has an effect when the listener object has a shorter lifetime than the dispatcher. It's a good idea to understand how to use it, but in practice I avoid it and simply write a method in my class that would remove all the added listeners.

Upvotes: 3

Related Questions