How to preload a file in Flex before the application initializes - apache-flex

Problem: An XML configuration file needs to be loaded at runtime and be ready when the application's createChildren() gets called. At the latest, because configuration values are needed to properly initialize child components. Preferably, I would like the configuration loading be complete before the application even gets created. In short, I want to do this:
load configuration, then
initialize the application using the loaded configuration.
I created a custom preloader to help solve this. But as it turns out, the application's createChildren() method already gets called during preloading, when the configuration is not yet guaranteed to be loaded. That is, before the custom preloader dispatches the COMPLETE event.
Thanks for any help in advance.

I found a solution to the problem. The key was to catch the preloader's FlexEvent.INIT_PROGRESS event, queue it, and stop its propagation until the configuration is fully loaded. This effectively stops the framework to proceed with application initialization. After the configuration loads, redispatch the queued events, letting the framework finish the preloading phase. Example code below (only relevant pieces):
public class PreloaderDisplay extends Sprite implements IPreloaderDisplay {
// mx.preloaders.IPreloaderDisplay interface
public function set preloader(preloader:Sprite):void {
// max priority to ensure we catch this event first
preloader.addEventListener(FlexEvent.INIT_PROGRESS, onInitProgress, false, int.MAX_VALUE);
startLoadingConfiguration();
}
private function onInitProgress(e:FlexEvent):void {
if (isConfigurationLoading) {
queuePreloaderEvent(e);
e.stopImmediatePropagation();
}
}
private function onConfigurationLoaded():void {
dispatchQueuedPreloaderEvents();
}
}
To use it in the application:
<mx:Application preloader="the.package.of.PreloaderDisplay">

The simplest way (I think) is to create a 'holder' canvas that will create the applications content after the context file is loaded, ie:
(psuedo code)
Application.mxml:
<mx:Canvas>
<mx:Script>
public function init():void{
loadXML();
}
public function handleXMLLoaded():void{
this.addChild(myApplicationContent);
}
</mx:Script>
</mx:Canvas>
MyApplicationContent.mxml
<mx:Canvas>
<!-- contains all your components etc -->
</mx:Canvas>

Related

FLex : unload swf file in SWFLoader

In Flex 3 I have a SWFLoader:
<mx:SWFLoader id="player" source="http://youtube.com/v/..." />
and after some time I invoke player.unloadAndStop(). And I always get this error:
ReferenceError: Error #1056: Cannot create property __tweenLite_mc on _swftest_mx_managers_SystemManager.
What does it mean and how to avoid this?
UPD: AIR 2 doesn't have this problem
Maybe try the Loader class? I'm not sure if it will help but I do all my loading via ActionScript. Generally speaking, I do "heavyWeight" programming/logic/cotrol stuff in ActionScript and leave Flex for more simplistic layout code. That is, flex puts things in place and actionscript controls it all. When loading clips in our Flex 3 project, I have control code along the lines of:
import flash.display.Loader;
private var loader:Loader;
public function init() {
loader = new Loader();
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadFailed);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadCompleted);
}
with calls to things like:
//here, pop returns a string like "/path/to/movie.swf"
loader.load(new URLRequest(clipsToPlay.pop()));
...
loader.unload();
contained in functions like:
private function loadNextClip():void {
if(clipsToPlay.length == 0) {
dispatchEvent(new PlayBackCompleteEvent(PlaybackCompleteEvent.ALL));
return;
}
loader.load(new URLRequest(clipsToPlay.pop()));
}
private function loadCompleted(event:Event):void {
currentClip = event.target.content as MovieClip;
loader.unload();
displayClip();
}
private function displayClip():void {
applyEffects();
currentClip.addEventListener(Event.ENTER_FRAME, monitorForCompletion);
addChild(currentClip);
}
I'm not sure if Loader can be used instead of SWFLoader but if so I hope that helps you or someone else, in some way...
EDIT:
I just looked it up and mx.controls.SWFLoader and flash.display.Loader have very similar functionality. I'd try using Loader, as prescribed above, and see if it fixes the problem. You could probably initialize the loader via MXML, too, but I wouldn't recommend it since it's not a visual component, I think it's better to let MXML handle visual things while ActionScript handles logical things.

Giving Flex MXML views their dependencies

I'm used to building applications using pure AS3. I always pass dependencies into the constructor of classes I make, but this method seems to not work out well for Flex MXML views.
It seems like I should define setters on the MXML class, which map to attributes in the tag/class instantiation. But using this method I cannot specify which properties are required and in what order I expect them etc.
What is the preferred method to give a Flex view it's dependencies?
A pattern I've used a couple times was to define a public init() method in the MXML which takes the argument that would normally have gone in the constructor. Then, whatever instantiates that MXML component is responsible for calling init() before using it.
Another way would be to create setters for the properties like you mentioned. In those setters store the values that are passed, then call invalidateProperties(). Then override the commitProperties() method in the MXML, and the first time that's called do your initialization (and maybe throw an exception if the needed properties weren't provided). As long as the user of your class sets all the properties before adding the component to the display list then it will work fine (I don't believe commitProperties() is called until after a component is added to the display list, either by being declared in MXML or by passing it to an addChild() call).
I haven't ever tried that second method (only just thought of it now), but it should work.
You can't force people to use parameters in the constructor, but you can force then to set properties before adding the item to the stage.
How's this:
<mx:HBox
added="{checkProps()}">
<mx:Script>
<![CDATA[
public var prop1:String;
public var prop2:String;
private function checkProps():void
{
if( !( prop1 && prop2 ) )
{
throw new Error( "Prop1 and prop2 must be set before "+
"adding this to the stage" );
}
}
]]>
</mx:Script>
</mx:HBox>
Realistically, if you're interested in forcing people to do something before adding it to the display list, then you're going to have to do something like this anyway.
There are a few things in Flex that you can override or listen to that are really important.
FlexEvent.CREATION_COMPLETE - set an eventListener for this (I usually do it in the constructor but you could do it in MXML as creationComplete attribute) and it acts like your constructor. Use getters and setters to pass through references to your dependencies as MXML attributes and store them locally then inside this handler you will apply them.
override protected function createChildren - this is called when it is time to add display list items to the component. You shouldn't do that during the constructor or creationComplete handlers. It is always tempting to addChild outside of this function but Adobe best practice is only to do so directly in this function.
override protected function updateDisplayList - this is where your drawing logic should happen (if there is any) or positioning/alpha/rotation/etc of children. This will get called if a CSS property changes, a child changes size or position or anything else that the Flex framework thinks may cause you to want to redraw the screen. You can force an updateDisplayList to get called by calling invalidateDisplayList
override protected function commitProperties - this is called when the dataProvider for a class is changed. Any time data within the component means you want to update internal data structures this should be called. You can force this to be called using invalidateProperties.
FlexEvent.ADDED_TO_STAGE - If you need to know when the component is actually added to the stage you can listen for this. In practice I can't remember ever actually using it ...
Always remember to call the super equivalents -- forgetting to do so will often cause the component to fail to appear at all (this happens to me at least 4 or 5 times a project). Also be aware that if you first invalidateProperties and then commitProperties and then invalidateDisplayList and then updateDisplayList you may see some jerkyness ... that is, invalidateDisplayList as soon as you know you'll want a redraw to avoid delay.
Also don't get too invested in Flex 3 since Flex 4 is just around the corner and it is quite a bit different. I have a feeling that much of this will no longer apply in the new component framework (names Spark).
edit a typical class stub:
package
{
import mx.containers.Canvas;
import mx.events.FlexEvent;
public class TestComponent extends Canvas
{
public function TestComponent()
{
super();
addEventListener(FlexEvent.CREATION_COMPLETE, init);
}
// acts as constructor
private function init(event:FlexEvent):void
{
// might as well be clean
removeEventListener(FlexEvent.CREATION_COMPLETE, init);
// do init stuff here
}
override protected function createChildren():void
{
super.createChildren();
// do any addChilds here that are necessary
}
override protected function commitProperties():void
{
super.commitProperties();
// update internal state when data changes
}
override protected function updateDisplayList(w:Number, h:Number):void
{
super.updateDisplayList(w, h);
// do any drawing, positioning, rotation etc.
}
}
}

flex 3 accessing main mxml from actionscript code

im writting an actionScript class to handle my web service calls. When i retrieve a result i want to call a setter method in my main mxml application. My problem is that i dont know how to access the methods in the actionScript section of my main mxml class from my actionscript class, any ideas?
David is right -- while you can access the public members of your Application.mxml object statically and from anywhere in your application, design-wise that's a bit of a no-no. It's better to strive for loose coupling between your objects, and the way that's done in the Flex idiom is generally to extend EventDispatcher and to dispatch events. So for example, your WebService wrapper might look something like this:
public class MyWrapperClass extends EventDispatcher
{
[Event(name="webserviceComplete", type="flash.events.Event")]
public function MyWrapperClass(target:IEventDispatcher=null)
{
super(target);
}
private function handleWebServiceLoadComplete(event:ResultEvent):void
{
dispatchEvent(new Event("webserviceComplete"));
}
public function doWork():void
{
// Load the service, etc., and ultimately call handleWebServiceLoadComplete()...
}
}
... and your Main.mxml file like this:
<mx:Script>
<![CDATA[
private function app_creationComplete(event:Event):void
{
var myWrapper:MyWrapperClass = new MyWrapperClass();
myWrapper.addEventListener("webserviceComplete", mywrapper_webServiceComplete, false, 0, true);
myWrapper.doWork();
}
private function mywrapper_webServiceComplete(event:Event):void
{
// Do the work you would've otherwise done in the public method
}
]]>
</mx:Script>
In this case, the end result is the same -- completing the web-service load triggers the function in Main.mxml. But notice how mywrapper_webServiceComplete() is declared privately -- it's not called directly by MyWrapperClass. Main.mxml simply subscribes (with addEventListener()) to be notified when MyWrapperClass is finished doing its work, and then does its own work; MyWrapperClass knows nothing about the details of Main.mxml's implementation, nor does Main.mxml know anything about MyWrapperClass other than that it dispatches a webserviceComplete event, and exposes a public doWork() method. Loose coupling and information hiding in action.
Good luck!
If your class is an UIComponent added to the component tree, then you can use its parentApplication attribute. Otherwise, use the static Application.application attribute, but only after the application initialization has completed. Earlier than that, the field is null. Private fields and methods obviously cannot be accessed. Elements declared in the MXML part with explicit ids are public.
Adding such a call creates a rigid binding, though. You might want to consider dispatching an event instead, and handling this event in the main application.
In case anyone has the same problem:
mx.core.FlexGlobals.topLevelApplication.YOUR_FUNCTION
is the syntax to access public functions within the main.mxml.

Passing flashvars-style parameters to a loaded SWF

I have a Flex 3 app (player v9) which loads a Flash SWF (AS3, also player v9) and needs to dynamically pass it a collection of parameters which are known at run-time. These are parameters that are normally passed via the flashvars element in an HTML page. The embedded movie accesses these parameters via the loaderInfo.parameters object.
I've tried using SWFLoader and Loader classes with no success in param-passing.
Relevant details:
It's a local program, and cannot rely on query string parameters.
I've mucked with setting loaderInfo.parameters["foo"] = "123" from the embedding code, but the parameter never seems to wind up in the embedded movie.
I cannot place extra parameter-passing machinery in the embedded movie(s), as they are created by third parties.
Passing this params in URL won't help, because they're taken using javascript code in the html-wrapper.
The 'flashVars' params are taken using the Application.application.parameters, so, you have to set these params manually in your case.
If you are using SWFLoader to load another app, you should create the object, that will represent the application loaded and apply all you need:
<mx:Script>
<![CDATA[
import mx.managers.SystemManager;
import mx.controls.Alert;
import mx.events.FlexEvent;
private var loadedApp:Application;
private function onLoadComplete(event:Event):void {
var smAppLoaded:SystemManager = SystemManager(event.target.content);
smAppLoaded.addEventListener(FlexEvent.APPLICATION_COMPLETE, onLoadedAppComplete);
}
private function onLoadedAppComplete(event:FlexEvent):void {
try {
loadedApp = Application(event.target.application);
if(!loadedApp) throw new Error();
loadedApp.parameters["param1"] = "value1";
} catch (e:Error) {
Alert.show("Failed to get application loaded.", "Error", Alert.OK);
}
}
private function onLoadError():void {
Alert.show("Failed to load an application.", "Error", Alert.OK);
}
]]>
</mx:Script>
<mx:SWFLoader
width="100%" height="100%"
source="./AppToLoad.swf"
complete="onLoadComplete(event)"
ioError="onLoadError()" securityError="onLoadError()" />
The reason is simple.
I've discovered this today.
In the component loaded via SWFloader has parentApplication or Aplication.application set to the top level application (this witch loads component via SWFLoader).
And the loaded component can see flashvars set to the top level application.
This is probably the cause that setting parameters in SWFLoader does not have any impact.
I've set proper flashvars on my toplevel application and they are also seen in the loaded one :-).
When embedding a SWF on a web page you can pass flashvars as parameters on the URL to the SWF, perhaps the same could work in your case? If the SWF is located at file:///some/path/to/a.swf try using file:///some/path/to/a.swf?hello=world&foo=bar. It might work.
Would have saved myself a lot of time today if I had found this answer first: AS3 Pass FlashVars to loaded swf.
Essentially: since Flash Player 10.2 it has been possible to pass flashvars along by setting them as parameters on the LoaderContext.

What restrictions does public/private have in actionscript functions?

I'm currently maintaining some flex code and noticed very many functions which are declared like:
private function exampleFunc():void {
....
}
These functions are in the global scope, and aren't part of any specific class, so it's a bit unclear to me what effect declaring them as private would have. What restrictions does the "private" qualifier have for functions like this?
The actionscript functions that are included in your mxmlc code will we available as a part of your mxmlc component, which behind the scenes is compiled into a class. Therefore marking them as private makes them inaccessible.
Here is an example to make that clear, say you have the following component, we'll call it FooBox:
<!-- FooBox.mxml -->
<mx:Box xmlns:mx="http://www.macromedia.com/2003/mxml">
<mx:Script><![CDATA[
private function foo():void {
lbl.text = "foo";
}
public function bar():void {
lbl.text = "bar";
}
]]></mx:Sctipt>
<mx:Label id="lbl">
</mx:Box>
I can now add FooBox to my application, and use it's functions:
<mx:Application
xmlns:mx="http://www.macromedia.com/2003/mxml"
xmlns:cc="controls.*"
>
<mx:Script><![CDATA[
private function init():void {
fbox.foo(); // opps, this function is unaccessible.
fbox.bar(); // this is ok...
}
]]></mx:Sctipt>
<cc:FooBox id="fbox" />
</mx:Application>
If the actionscript functions are included in your Main Application file, the I think you can call the functions from an child control through the Application.application object, something like:
Application.application.bar();
if the bar function was placed in the main mxmlc code.
What do you mean by global scope? Are these functions declared in the main MXML file?
In general, private means that functions can only be called from within the class that declares them.
But, when you put it in a actionscript file .as is it still compliled into a class ?
Because asdoc doesn't like it.

Resources