Troubleshooting Actionscript in a Flex Component
Using an Actionscript class within a Flex component can be a little tricky. The first error I ran into was:
Error #1009: Cannot access a property or method of a null object reference.
This was a result of using a stage reference within the class to set up boundaries. Since I no longer had access to the stage properties I created two variables within the class to pass the Flex canvas size on instantiation.
The second error I encountered was:
Error #1034: Type Coercion failed: cannot convert classes::Sprite@8b69259 to mx.core.IUIComponent.
This is because the Flex component will only accept a UIComponent as a child. Since our Actionscript class extends a Sprite we’ll need to place it within one first:
var bouncingBall:UIComponent = new UIComponent(); bouncingBall.addChild(new BouncingBall(myCanvas.width, myCanvas.height)); myCanvas.addChild(bouncingBall);
This creates a reference UIComponent that we will place our BouncingBall class into which we can now add to our canvas.
An alternative method is to use the rawChildren of the canvas and add the sprite directly to it’s display list. While this works fine, it does seem a bit obscure/ugly. But whatever floats your boat:
var bouncingBall:BouncingBall = new BouncingBall(myCanvas.width, myCanvas.height); myCanvas.rawChildren.addChild(bouncingBall);
The MXML is rather straightforward, though you’ll want to include a clipping rectangle on the canvas otherwise the ball will be dragged all over the screen.
The source code for the above example is available here.