fx:script for AS3 and MXML for? - apache-flex

I find the flexibility in using fx:script to get all AS3 see each other easily but I have a few MXML module, some actionscript from main.mxml want to access the ID in specific module such as module1.mxml. How do I get it to work?

Assuming you have a module1.mxml is a defined component in main.mxml, you can give it an ID and reference public variables and functions inside of it. The following shorthand code demonstrates this.
<mx:Application creationComplete="creationCompleteHandler()">
<fx:Script>
function creationCompleteHandler() : void
{
m1.initializeModule();
}
</fx:Script>
<module1 id="m1" />
</mx:Application>

Related

FastInject not detecting objectId in Parsley

I have just started using Parsley recently and I ran into this issue. The thing is I have a custom component in my project, which is "configured" by Parsley and has a piece of code as follows:
<fx:Script>
<![CDATA[
...
[Inject(id="dateFormatter")]
[Bindable] public var dateFormatter:DateFormatter;
...
]]>
</fx:Script>
<fx:Declarations>
<parsley:Configure />
</fx:Declarations>
My problem is that I don't want Parsley to configure the component entirely. I want to simply use FastInject in MXML, instead of using Configure, like:
<parsley:FastInject objectId="dateFormatter" property="dateFormatter" type="{DateFormatter}" />
From what I found when I searched online, the objectId in FastInject is the same as [Inject(id="dateFormatter")]. Here's the source for that. Please correct me if I am wrong :).
But when I use it, I hit the following error:
Error: More than one object of type mx.formatters::DateFormatter was registered
Does this mean that the ID of the property being injected is not being picked up? It works fine when I configure the whole component and use the Inject meta-tag, but I don't want to configure the whole component.
Can someone suggest a solution?
FastInject by id works if objects declared in the context have an id.
Context configuration
<fx:Declarations>
<foo:FooBar1 />
<foo:FooBar2 id="fooBar2" />
</fx:Declarations>
FastInject in your component
<fx:Declarations>
<parsley:FastInject injectionComplete="handlerInjectComplete(event)">
<parsley:Inject property="foobar1" type="{FooBar1}" />
<parsley:Inject property="foobar2" objectId="fooBar2"/>
</parsley:FastInject>
</fx:Declarations>
<fx:Script>
<![CDATA[
[Bindable]
public var foobar1:FooBar1;
[Bindable]
public var foobar2:FooBar2;
protected function handlerInjectComplete(event:Event):void
{
if(foobar1) trace("foobar1 available");
if(foobar2) trace("foobar2 available");
}
]]>
</fx:Script>
This works for me.
Parsley FastInject gets confused when you inherit B from class A and want to inject both by id, while specifying type.
You need to use only one of objectId / type attributes of FastInject

Disable warning only in one place

In an MXML code
<fx:Script>
public var data:ArrayCollection = new ArrayCollection();
</fx:Script>
<s:DataGroup dataProvider="{data}" />
I'm getting a warning:
Data binding will not be able to detect assignments to "data"
I know that the data provider will be never changed in this case, and want to suppress this warning in this case, but I don't want to completely disable it, -show-binding-options=false in all project is not an option.
How to disable a warning only in one place? Disabling for the whole file is not so good, but acceptable.
How about just making your data variable bindable? Something like:
<fx:Script>
[Bindable]
public var data:ArrayCollection = new ArrayCollection();
</fx:Script>
<s:DataGroup dataProvider="{data}" />
Instead of using <fx:Script></fx:Script> you could use <fx:Declarations></fx:Declarations>. Any object declared in that MXML element is bindable implicitly. Here's how your code will look like then:
<fx:Declarations>
<s:ArrayCollection id="data" />
</fx:Declarations>
<s:DataGroup dataProvider="{data}" />
Additionally it becomes much more readable and there's no mix of ActionScript and MXML. Because your collection is declared as public it makes difference whether to use ActionScript with [Bindable] or using MXML.
BTW, a general recommendation for cleaner code is to separate ActionScript completely from MXML. For instance in my projects I create a separate ActionScript file for each MXML component in the form <NameOfComponent>Includes.as.

Separating MXML and Actionscript

From this tutorial http://www.brighthub.com/internet/web-development/articles/11010.aspx
I found the code below. Is there a way to break this out so the mxml file just has the mxml, and the code between the script tags is put in an actionscript file?
Thanks.
-Nick
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute"
width="600"
height="400"
frameRate="100"
creationComplete="CreationComplete()"
enterFrame="EnterFrame(event)">
<mx:Script><![CDATA[
public function CreationComplete():void
{
}
public function EnterFrame(event:Event):void
{
}
]]></mx:Script>
</mx:Application>
There are several ways of achieving this in Flex:
Put the AS code in a .as file and use the "source=yourfile.as" attribute in the Script tag:
<mx:Script source="yourfile.as" />
You can also use the includes="yourfile.as" declaration w/in the Script tag:
<mx:Script
<![CDATA[
include "yourfile.as";
//Other functions
]]>
</mx:Script>
Use a Code-Behind pattern where you define the code in an AS file which extends the visual component you want your MXML file to extend. Then your MXML file simple extends the AS file and you have (via inheritance) access to all the code. It would look something like this (I'm not sure if this would work for the main MXML file which extends Application):
AS File:
package {
public class MainAppClass {
//Your imports here
public function CreationComplete():void {
}
public function EnterFrame(event:Event):void {
}
}
}
MXML File:
<component:MainAppClass xmlns:component="your namespace here"
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute"
width="600"
height="400"
frameRate="100"
creationComplete="CreationComplete()"
enterFrame="EnterFrame(event)">
</component:MainAppClass>
Use a framework to inject the functionality you are looking for as a type of "model" which contains the data-functionality you will use. It would look something like this in Parsley:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute"
width="600"
height="400"
frameRate="100"
creationComplete="model.CreationComplete()"
enterFrame="model.EnterFrame(event)">
<mx:Script>
<![CDATA[
[Inject]
[Bindable]
public var model:YourModelClass;
]]>
</mx:Script>
</mx:Application>
Two frameworks which come to mind which can help w/injection are Mate or Parsley.
I'm not sure if the code-behind pattern works with the main MXML file (which extends Application), so if you're having problems, you might try breaking out the content in your Main MXML file into a separate component which is included in Main. It might look something like this:
Main.mxml:
<mx:Application blah,blah,blah>
<component:YourComponent />
</mx:Application>
YourComponent.mxml:
<component:YourComponentCodeBehind creationComplete="model.creationComplete()"...>
//Whatever MXML content you would have put in the Main file, put in here
</component:YourComponentCodeBehind>
YourComponentCodeBehind.as
package {
class YourComponentCodeBehind {
//Whatever AS content you would have put in the Main .as file, put in here
}
}
From what I've been able to gather from Flex architecture, this is a very common way of setting up your application: your main MXML includes a single "view" which is the entry-point to the rest of your application. This view the contains all other views which comprise the app.
Hope that makes sense :)

How can I target a Flex 3 datagrid in MXML from Actionscript?

I have a datagrid defined in an mxml file (flex 3):
I am using an external class to connect to a sqlite database and generate some results (this is working and I can trace the results).
How can I target the datagrid generated in the mxml from the external class? I have tried:
Application.application.resultsGrid.dataProvider = results.data;
And get 'Error: Access of undefined property Application.' from the amxmlc compiler.
I've also tried:
[Bindable]
public var resultsGrid:DataGrid;
In the class properties.
Looks like I needed to include import mx.core.*; and it now works.
I don't really understand your answer. Am I not binding the dataprovider property by doing:
Application.application.resultsGrid.dataProvider = result.data; ?
I'm from a PHP background and familiar with OOP in that environment so the idioms in Flex are quite strange to me.
as brd664 says, what you are actually doing in
Application.application.resultsGrid.dataProvider = result.data;
is actually an assignment. It's just like assigning a value to variable as in
var a : uint = 1;
Binding gives you a little more structure and allows you to populate multiple components based on a single property update. There's a ton of other benefits from binding and probably too much to cover in this post.
Here is a quick and simple example of how binding works. Note that there is one property that is bindable... when you click the button it sets that property to the value of whatever is in the textInput. This update then causes the bindings to fire and updates anything that has been bound to that property. It's one of flex's biggest features (it's also used extensively in silverlight and wpf and probably a load of other technologies that i'm not aware of). Anyway... have a play with it and see if you can get your component to update from a binding.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal">
<mx:Script>
<![CDATA[
private var _myData : String
[Bindable]
public function get myData() : String
{
return _myData;
}
public function set myData(value : String) : void
{
_myData = value;
}
private function clickHandler(event : MouseEvent) : void
{
myData = myTextInput.text;
}
]]>
</mx:Script>
<mx:VBox>
<mx:HBox>
<mx:Label text="{myData}" />
<mx:Label text="{myData}" />
<mx:Label text="{myData}" />
</mx:HBox>
<mx:TextInput id="myTextInput" text="TYPE HERE" />
<mx:Button label="CLICK TO BIND" click="clickHandler(event)" />
</mx:VBox>
</mx:Application>
Update: The phrasing of your question confused me :(
If you need to populate the datagrid with from you db, you really should be looking at binding the dataProvider property.

Access to elements defined in MXML from External AS

I have a MXML with a form, and inside it, two TextInputs. I hate having any piece of code inside the MXML file (I come from a JavaScript formation) so I use a
mx:Script source="external.as"
tag to include any code used in any MXML file. The problem is that if I have this code on the external.as file:
private function populateFromForm():void{
var vo:ValidObject= new ValidObject();
vo.market = marketInput.text;
vo.segment = segmentInput.text;
vo.priceLow = priceLowInput.text;
vo.priceHigh = priceHighInput.text;
}
Where marketInput, segmentInput, priceLowInput and priceHighInput are TextInputs defined in the MXML file. When I try to complile I get a 1120: Access to undefined property XXXXX
I have tried adding this lines prior to the function:
public var marketInput:TextInput;
public var segmentInput:TextInput;
public var priceLowInput:TextInput;
public var priceHighInput:TextInput;
But instead I get a 1151:A conflict exists with definition XXXX in namespace internal which makes perfect sense.
Is there a way to do this without having to pass all the input references to the function as parameters of it?
You need to create a reference to an instance of the TextInputs' parent container, and then use that reference to accsess the TextInputs and their properties. I think we need some clarification on your file structure. How are you creating the instance of the parent container? I'm thinking this is what you need to do:
MyForm.mxml:
<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:TextInput id="marketInput" />
<mx:TextInput id="segmentInput" />
<mx:TextInput id="priceLowInput" />
<mx:TextInput id="priceHighInput" />
</mx:VBox>
SaveVOContainer.as:
package
{
public class SaveVoContainer extends Container
{
private var myForm:MyForm = new MyForm();
public function SaveVOContainer
{
this.addChild(myForm);
}
private function populateFromForm():void{
var vo:ValidObject= new ValidObject();
vo.market = myForm.marketInput.text;
vo.segment = myForm.segmentInput.text;
vo.priceLow = myForm.priceLowInput.text;
vo.priceHigh = myForm.priceHighInput.text;
}
}
}
Doing a "code-behind" is painful in Flex. There is no concept of partial classes or the flexibility of prototypal inheritance as in Javascript. Google for "code-behind in flex" for many resources.
I think it's better you get used to the idea of embedding code in mxml. Use script tags avoiding inline code as much as possible. If you have to write a lot of code within MXML, perhaps you may want to re-factor the code into multiple custom components. Bonus points if they are reusable.
The canonical way to do code-behind in Flex is via inheritance. Here's a good explanation from the docs: http://learn.adobe.com/wiki/display/Flex/Code+Behind. In a nutshell:
Declare an ActionScript class to use as your base class.
Set the base class as the root container in your MXML file.
For any controls declared in your MXML file, you have to redeclare them as public members of the base class using the exact same name (exactly as you are doing above for your script block with source tag, only it works :-)
So, your ActionScript file:
package mypackage
{
import mx.controls.TextInput;
public class myClass extends WindowedApplication
{
public var marketInput:TextInput;
private function populateFromForm():void{
/* As above */
}
}
}
And the corresponding MXML file:
<?xml version="1.0" encoding="utf-8"?>
<custom:myClass xmlns:custom="mypackage.*"
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<mx:TextInput id="marketInput"/>
</custom:myClass>
Et cetera for your other TextInput controls. And now your populateFromForm function should work.
It is kind of heinous to have to redeclare the same entities twice, but it's not quite the bag of hurt the earlier respondent made it out to be (although it's possible this changed in Flex 4 to make it less painful than it was).
import this in .AS:
import mx.core.Application;
in the .AS use this:
mx.core.Application.application.component.property = value;
mx.core.Application.application.myText.text = 'test';
do you have a script tag in your mxml file that points to your ActionScript file?
<mx:Script source='includes/foo.as' />

Resources