Quantcast
Viewing all articles
Browse latest Browse all 10

Note to Self – #2: Adding eventlisteners after event has fired

You can’t add event listeners to an object that is returned from a method and expect to receive the events that are dispatched within the same method that returns the object to which you are adding event listeners.

This on is perhaps not so obviously stated, but can be made more clear via some code (hopefully):

  1.  
  2.  
  3. myObject:MyObject = new Object(fooParam);
  4. myObject.addEventListener("myEventType", myCallBackFunction);
  5.  
  6. //where MyObject Class looks like this:
  7.  
  8. public class MyObject extends EventDispatcher
  9.         {
  10.                 // constructor
  11.                 public function MyObject (fooParam:String, target:IEventDispatcher=null)
  12.                 {
  13.                         super(target);
  14.                         // do some stuff and then dispatch event
  15.                         dispatchEvent(new MyEvent(MyEvent.MY_EVENT_TYPE));
  16.                 }
  17.  

This just won’t work.

Better to do something like:

  1.  
  2.  
  3. myObject:MyObject = new Object();
  4. myObject.addEventListener("myEventType", myCallBackFunction);
  5. myObject.doStuff(fooParam);
  6.  
  7. //where MyObject Class looks like this:
  8.  
  9. public class MyObject extends EventDispatcher
  10.         {
  11.                 // constructor
  12.                 public function MyObject (target:IEventDispatcher=null)
  13.                 {
  14.                         super(target);
  15.                  }
  16.  
  17.                public function doStuff(fooParam:String):void {
  18.                         // do some stuff and then dispatch event
  19.                         dispatchEvent(new MyEvent(MyEvent.MY_EVENT_TYPE));
  20.                }
  21.  

That should work and not cause you to chase your tail trying to figure out why things are not getting dispatched or not being responded to by an eventListener
Image may be NSFW.
Clik here to view.
:)


Viewing all articles
Browse latest Browse all 10

Trending Articles