Dispatching custom events between child SWFs in AS3
I've written about this before, but this time around I have an answer to this one. The issue goes a little something like this:
a parent SWF
a child SWF, dispatches a custom event
another child swf, nested in either the parent or the other child, listens for that custom event.
The error you'll receive is a type coercion error that looks like a mistake - can't convert [custom event name] to [custom event name]. So what gives? They're the same class, both SWF files have imported the event class correctly, yet they are colliding through the event dispatch. Well, it turns out it is a security violation due to the way in which the SWF was loaded. Change your loader context to new LoaderContext(false, ApplicationDomain.currentDomain) when loading in those child SWFs and suddenly they can talk to each other more openly than before and type checking correctly returns that all important 'true' - in other words, no coercion error. All of those imported classes match up - and you can even instantiate objects of a type defined in the other child SWF without importing it into your class. To get Flash to export it without referencing it though requires a SWC file for the SWF to reference the classes from (CS4 modified this process a bit with the ability to specify external libs, and Flex has had the same functionality for a while i believe). Colin Moock's Essential Actionscript has a chapter on doing just that, right at the end of the book. If you're interested in that process, he says it better than i ever could.
FYI - the fix mentioned in my previous post on the subject is still valid if you can't/don't want to change the application domain for the loader. Adding the reference to the document class of the top level parent SWF still rectifies the issue.



September 20th, 2011 - 14:27
you have 2 swf. parent swf and child swf. Parent swf import your CustomEvent class, and child import CustomEvent class. When the two swf create a new istance of CustomEvent to dispatch Event, the CustomEvent class for the parent swf is not the CustomEvent class of the Child… even those look the same.
when the parent swf load the child, parent must load child CustomEvent class definition inside the loader.loaderinfo.getDefinition(CustomEvent class) , so the parent swf will dispatch custom event of the REAL CustomEvent class of the child.