flex 3 accessing main mxml from actionscript code - apache-flex

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.

Related

binding exists property in actionscript

how can i do binding exists property in actionscript e.g. i want image still in middle aplication..in mxml i do this simple as <mx:Image source="image.jpg" x="{this.width/2}"/> ...i don't know how can i do this simple in actionscript without event handlers... i put this code to application_creationCompleteHandler..
something like var image:Image = new Image(); image.source="image.jpg"; image.x=this.width/2; or have i put this to another function?? i can't do e.g. updateComplete event handler and change it there...
thanks
pavel
Check the BindingUtils class and its bindSetter method. You can bind a setter to the "width" property and adjust the x property of your image in that handler.
Considering that as3 is OO language i always start from something like this:
public class App extends Sprite {
public function App() { //constructor
super(); //extends class constructor
loading(); //your function were you set all elements properties
}
}

create interface object in mxml

Let's say I have an interface
public interface IFoo {
...
}
and I have several implementing classes
public class Foo implements IFoo {
...
}
...
public class Bar implements IFoo {
...
}
...
public class Baz implements IFoo {
...
}
I want to reference IFoo in MXML like this
<ns:IFoo id="myfoo"/>
and have it be instantiated at runtime by a factory.
However, the compiler won't let me do this-- it's trying to do "new IFoo" in the generated ActionScript.
How to get around this? How can I use an interface and a factory purely in MXML?
Declaring an MXML child instantiates an object of that type - you can't simply declare a property in MXML without associating an instance with it.
Given that - there's no way to achieve the equivalent of
public var myFoo:IFoo;
in your MXML.
As James pointed out, you can use a ClassFactory to acheive the following:
<mx:ClassFactory class="{Foo}" id="fooFactory" />
but you would be required to call fooFactory.newInstance() to get an IFoo.
You can implement interfaces in MXML components with the implements="IFoo" attribute in the component's root node.
Edit:
Sorry, I missunderstood your question. I don't know a way to implement a factory in pure mxml. I guess you have to use Actionscript or mxml states to achieve a similar behaviour.
Check out ClassFactory. It is how things like item renderers are instantiated.

How to preload a file in Flex before the application initializes

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>

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.
}
}
}

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