I came across a strange situation over the weekend where a custom event being broadcast through dispatchEvent() was not being caught by the registered listener object. To make things even more bizarre, hasEventListener() definitely showed the event as registered, and I could even trace the type out through willTrigger().
Relevant example code is below:
1
2
3
4
5
6
7
8
| private function fileDoesNotExist(e:IOErrorEvent):void {
textSlide = new TextSlide(data.comment);
textSlide.addEventListener("slideReady", writeIt);
}
private function writeIt(e:Event):void {
// Okay!
} |
After a bunch of experimentation and comparing this structure with similar classes, I found that simply delaying the event dispatcher with a Timer by a few milliseconds resulted in a successful dispatch and capture.
Now, the class transmitting the event is a very simple one that simply has a constructor function that renders some bitmapData from injected data (severely shortened for this example):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
| package edu.du.image {
import edu.du.image.ResizeImage;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import flash.text.TextField;
import flash.utils.Timer;
[Event(name="slideReady", type="flash.events.Event")]
public class TextSlide extends Bitmap {
public function TextSlide(t:String, bitmapData:BitmapData=null, pixelSnapping:String="auto", smoothing:Boolean=true){
super(bitmapData, pixelSnapping, smoothing);
/*
perform a set of processes to render text to bitmapData
almost all is removed in this example
you get the idea...
*/
var timer:Timer = new Timer(500, 1);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, eGo);
timer.start();
}
private function eGo(e:TimerEvent):void {
dispatchEvent(new Event("slideReady"));
}
}
} |
Putting the Timer delay on there fixes everything. The only thing I can think of is that the constructor function must execute so quickly that the listener on the parent just hasn’t completely registered yet!
One of those things that can drive you nuts and waste hours of time.