Code behind for a flex application - actionscript-3

I'm working on Flex project and having problems with "connecting" the code-behind to the mxml file (It actually worked before in another project). Both files are in the default package.
Hydw.mxml:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" xmlns="*">
<s:TextArea id="txt_log" x="34" y="171" width="225" height="217"/>
</s:Application>
Hydw.as:
package
{
import flash.events.*;
import flash.external.*;
import flash.media.*;
import mx.controls.TextArea;
import mx.core.*;
import mx.events.*;
import spark.components.*;
public class Hydw extends spark.components.Application
{
public var txt_log:spark.components.TextArea;
public function Hydw ()
{
super();
addEventListener(FlexEvent.CREATION_COMPLETE, this.creationCompleteHandler);
}
private function creationCompleteHandler(param1:FlexEvent) : void
{
WriteToLog("creationCompleteHandler");
}
public function WriteToLog(s:String) : void
{
txt_log.text += s + "\n";
}
I run the application (after releasing) and I see nothing in the TextArea. Why?
By the way, I'm having trouble with the debugging for now, so I can't tell where's the failure exactly.

Obviously it didn't work. There need to make some changes in ActionScript and mxml file.
First: Remove package and class from ActionScript file like:
import mx.events.FlexEvent;
public function creationCompleteHandler(param1:FlexEvent) : void
{
WriteToLog("creationCompleteHandler");
}
public function WriteToLog(s:String) : void
{
txt_log.text += s + "\n";
}
Because It is in default package there isn't required to defined package and class.
Second:
Remove public var txt_log:spark.components.TextArea; from as file. Because it will conflict txt_log with id of textArea in mxml file.
Third:
Remove addEventListener(FlexEvent.CREATION_COMPLETE, this.creationCompleteHandler); from as file and give creation complete event in mxml file. like:
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
creationComplete="creationCompleteHandler(event)">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script source="Hydw.as" />
<s:TextArea id="txt_log" x="34" y="171" width="225" height="217"/>
</s:Application>
And another thing is you forget to include as file inside mxml. like:
<fx:Script source="Hydw.as" />
Hope you understand and help to move forward.

This is what you want
Hydw.mxml
<?xml version="1.0" encoding="utf-8"?>
<abstract:Hydw xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:abstract="test.pack.abstract.*"
minWidth="955" minHeight="600">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:TextArea id="txt_log" x="34" y="171" width="225" height="217"/>
</abstract:Hydw>
and your Hydw.as:
package test.pack.abstract
{
import mx.events.FlexEvent;
import spark.components.Application;
import spark.components.TextArea;
[Bindable]
public class Hydw extends Application
{
public var txt_log:TextArea;
public function Hydw()
{
super();
addEventListener(FlexEvent.CREATION_COMPLETE, init);
}
public function init(evt:FlexEvent):void
{
}
}
}
any visual component used in .mxml code you want to use in .as class
must be declared as public binded variable in your .as class or simply declare your .as class as [Bindable]
That's All

Related

Main application can't capturing custom event Flex

I have a problem when despatching an custom event from my "ItemRendered" to "Main application",the function "avatarSelectedHandler()" is not called when I click in the "CheckBox" (ItemRendered) located in the "DataGrid", I followed the official doc adobe but unfortunately I have not led to a solution.
below my code :
Try.mxml(Main application)
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="initApps()">
<fx:Script>
<![CDATA[
import entity.Avatar;
import events.AvatarSelected;
import mx.collections.ArrayCollection;
import mx.controls.Alert;
[Bindable]
private var listAvatar:ArrayCollection=new ArrayCollection();
public function initApps():void{
getAvatar();
avatarColumn.addEventListener(AvatarSelected.SELECTED_AVATAR,avatarSelectedHandler);
//avatarGrid.addEventListener(AvatarSelected.SELECTED_AVATAR,avatarSelectedHandler);
if(avatarColumn.hasEventListener(AvatarSelected.SELECTED_AVATAR))
Alert.show("EventListener OK ");
}
public function avatarSelectedHandler(event:AvatarSelected):void
{
Alert.show("L'evenement est bien traité sur main");
}
public function getAvatar():void{
var date:Date=new Date();
var avatar1:Avatar=new Avatar();
avatar1.idAvatar=4562;
avatar1.pseudo="X";
var avatar2:Avatar=new Avatar();
avatar2.idAvatar=659;
avatar2.pseudo="Y";
listAvatar.addItem(avatar1);
listAvatar.addItem(avatar2);
}
]]>
</fx:Script>
<s:DataGrid x="158" y="177" width="649" height="194" fontFamily="Times New Roman" id="avatarGrid"
fontSize="15" requestedRowCount="4" textAlign="center" dataProvider="{listAvatar}">
<s:columns>
<s:ArrayList>
<s:GridColumn dataField="isAvatar" headerText="Id" ></s:GridColumn>
<s:GridColumn dataField="pseudo" headerText="Pseudo"></s:GridColumn>
<s:GridColumn headerText="Selectionner" width="100" itemRenderer="rendered.CheckRendered" id="avatarColumn"></s:GridColumn>
</s:ArrayList>
</s:columns>
</s:DataGrid>
</s:Application>
My ItemRendered "CheckRendered.mxml"
<?xml version="1.0" encoding="utf-8"?>
<s:GridItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
width="50" height="27" clipAndEnableScrolling="true">
<fx:Metadata>
[Event(name="avatarSelected", type="events.AvatarSelected")]
</fx:Metadata>
<fx:Script>
<![CDATA[
import entity.Avatar;
import events.AvatarSelected;
import mx.controls.Alert;
protected function cBox_clickHandler(event:MouseEvent):void
{
var eventAvatar:AvatarSelected=new AvatarSelected("avatarSelected",Avatar (data));
dispatchEvent(eventAvatar);
}
]]>
</fx:Script>
<s:CheckBox id="cBox" horizontalCenter="0" click="cBox_clickHandler(event)"/>
</s:GridItemRenderer>
My custom event "AvatarSelected.as"
package events
{
import entity.Avatar;
import flash.events.Event;
import mx.states.OverrideBase;
public class AvatarSelected extends Event
{
public static const SELECTED_AVATAR:String = "avatarSelected";
public var avatar:Avatar;
public function AvatarSelected(type:String, avatar:Avatar)
{
super(type);
this.avatar =avatar;
}
}
}
My VO "Avatar.as"
package entity
{
//[Bindable]
//[RemoteClass(alias="entity.Avatar")]
[Bindable]
public class Avatar
{
public var idAvatar:Number;
public var pseudo:String;
}
}
I opted for another way to capture the event, I created a class SkinDataGrid that extends GridColumn to accept the event as an argument, but it does not work yet!
DataGrid on the Main Application:
<s:DataGrid x="171" y="333" width="649" height="194" fontFamily="Times New Roman" id="avatarGridII"
fontSize="15" requestedRowCount="4" textAlign="center" dataProvider="{listAvatar}">
<s:columns>
<s:ArrayList>
<skin:SkinDataGrid dataField="isAvatar" headerText="Id" ></skin:SkinDataGrid>
<skin:SkinDataGrid dataField="pseudo" headerText="Pseudo"></skin:SkinDataGrid>
<skin:SkinDataGrid headerText="Selectionner" width="100" itemRenderer="rendered.CheckRendered" id="avatarColumnII" avatarSelected="avatarSelectedHandler(event)"></skin:SkinDataGrid>
</s:ArrayList>
</s:columns>
</s:DataGrid>
SkinDataGrid.as
package skin
{
import spark.components.DataGrid;
import spark.components.gridClasses.GridColumn;
[Event(name="avatarSelected", type="events.AvatarSelected")]
public class SkinDataGrid extends GridColumn
{
public function SkinDataGrid()
{
super();
}
}
}
any idea ?
Thank you in advance.
You don't specify what kind of problem do you have (type of error), but from looking at the code I find suspicious, that function avatarSelectedHandler has as argument of MouseEvent type, when you assign it as handler of AvatarSelected type.
You also can try to dispatch this event with bubbling enabled (by default it's set to false in the Event class constructor).
In your case, the AvatarSelected constructor can be changed to smth like that:
public function AvatarSelected(type:String, avatar:Avatar, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
this.avatar =avatar;
}
And event creating would be like this (attention on the third parameter in the AvatarSelected()):
var eventAvatar:AvatarSelected = new AvatarSelected("avatarSelected", Avatar (data), true);

UI component form Flex to Air

In Flex application I have found a way to save target object to "string";
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.events.FlexEvent;
import mx.rpc.xml.SimpleXMLEncoder;
import mx.utils.ObjectUtil;
import mx.utils.XMLUtil;
protected function button1_clickHandler(event:MouseEvent):void
{
var fr:FileReference = new FileReference();
var ba:ByteArray = new ByteArray();
ba.writeObject(container);
fr.save(ba);
}
]]>
</fx:Script>
<s:BorderContainer id="container" x="68" y="64" width="341" height="257">
<s:Label x="69" y="83" width="257" height="124" text="Label"/>
</s:BorderContainer>
<s:Button x="68" y="329" label="SAVE" click="button1_clickHandler(event)"/>
Is there a way to read that file and show it as UIComponent in AIR?
This is my try:
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.FileFilter;
import flash.net.FileReference;
import flash.utils.ByteArray;
import spark.components.BorderContainer;
private var fr:FileReference;
private function onLoadFileClick():void
{
fr = new FileReference();
fr.addEventListener(Event.SELECT, onFileSelect);
fr.addEventListener(Event.CANCEL,onCancel);
fr.browse();
}
private function onFileSelect(e:Event):void
{
fr.addEventListener(Event.COMPLETE, onLoadComplete);
fr.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
fr.load();
}
private function onCancel(e:Event):void
{
trace("File Browse Canceled");
fr = null;
}
private function onLoadComplete(e:Event):void
{
var data:ByteArray = fr.data;
//read the bytes of the file as a string and put it in the
//textarea
//outputField.text = data.readUTFBytes(data.bytesAvailable);
//var obj:BorderContainer = data.;
cc = data.readObject();
//clean up the FileReference instance
fr = null;
}
//called if an error occurs while loading the file contents
private function onLoadError(e:IOErrorEvent):void
{
trace("Error loading file : " + e.text);
}
]]>
</fx:Script>
<mx:Button label="Load Text File" right="10" bottom="10" click="onLoadFileClick()"/>
<mx:TextArea right="10" left="10" top="370" bottom="40" id="outputField"/>
<s:BorderContainer id="cc" x="130" y="99" width="200" height="200">
</s:BorderContainer>
</s:WindowedApplication>
And I'm getting this error:
TypeError: Error #1034: Type Coercion failed: cannot convert Object#6f2bc41 to spark.components.BorderContainer at primi/onLoadComplete()[C:\Users\user\Adobe Flash Builder 4.5\primi\src\primi.mxml:51]
Any solution would will be fine... as long it works :)
You need to register a class alias for BorderContainer before writing to the ByteArray. Otherwise the object's type cannot be preserved and the container is written as an ordinary Object to the ByteArray.
Check the documentation for registerClassAlias() to get detailed information about how to read/write (or with the more common terms: serialize/deserialize) strongly typed objects in ActionScript.
And when I'm right, you need to register the class alias in both applications the Web-based one and AIR.

Dynamically selecting a static embedded image?

Here's my current situation:
I have images embedded on a class.
package system
{
public class Embedded
{
[Embed(source="assets/srcorangeboxidle.png")]
public static const btnSrcOrangeBoxIdle:Class;
[Embed(source="assets/srcorangeboxpressed.png")]
public static const btnSrcOrangeBoxPressed:Class;
[Embed(source="assets/hl1idle.png")]
public static const btnHL1Idle:Class;
[Embed(source="assets/hl1pressed.png")]
public static const btnHL1Pressed:Class;
public function Embedded(){}
}
}
Now on my main MXML file, I have the following.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark">
<fx:Script>
<![CDATA[
import system.Embedded;
protected function toggleButtonState(target:Object,pressed:Boolean=false):void
{
var baseImageName:String = target.id.toString();
if (!pressed) {
target.source = Embedded.[baseImageName+"Idle"];
} else {
target.source = Embedded.[baseImageName+"Pressed"];
}
}
]]>
</fx:Script>
<s:Image id="btnSrcOrangeBox" x="107" y="245" source="{Embedded.btnSrcOrangeBoxIdle}" mouseDown="toggleButtonState(btnSrcOrangeBox,true)" mouseUp="toggleButtonState(btnSrcOrangeBox,false)"/>
<s:Image id="btnHL1" x="107" y="355" source="{Embedded.btnHL1Idle}" mouseDown="toggleButtonState(btnHL1,true)" mouseUp="toggleButtonState(btnHL1,false)"/>
</s:Application>
As you can tell, the above codes don't seem to do the trick. I just want to dynamically select which Embedded.* class to select. Any help or hint will be greatly appreciated.
Remove the dot after the class name. The following should work:
target.source = Embedded[baseImageName + "Idle"];

changing component properties of SkinnableComponent in Actionscript

Flex 4 separates the visual components into the skins. So how do we access those visual elements from Skinnable component? Here is my code:
<?xml version="1.0" encoding="utf-8"?>
<s:SkinnableComponent xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" skinClass="skins.brushedSkin"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
import mx.controls.TextInput;
private var txt:String;
public function setText(s:String) {
txt = s;
// the following line doesn't work
var input:TextInput = this.skin.getChildByName("msg") as TextInput;
input.text = s;
}
]]>
</fx:Script>
</s:SkinnableComponent>
I just need to set the text in the TextInput in the brushedSkin skin. But I have no idea how to do this in Flex 4.
First you must specify in your SkinnableComponent the so called Designer-Developer Contract.
Then you should wait for your component to finish its instantiation in order to access its skin parts.
In your particular case you change your code in the following way:
<?xml version="1.0" encoding="utf-8"?>
<s:SkinnableComponent xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" skinClass="skins.brushedSkin"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
import mx.controls.TextInput;
[SkinPart(required="true")]
public var input:TextInput;
private var txt:String;
public function setText(s:String) {
txt = s;
if (initialized)
input.text = txt;
}
]]>
</fx:Script>
</s:SkinnableComponent>
Then ensure that your skin class contains the following declaration (probably you just need to rename the msg-TextInput to input):
<s:TextInput id="input"/>

Failing to import a class in ActionScript

Here is the error I get:
1046: Type was not found or was not a compile-time constant: fbAPI.
Here is my MXML:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="startGame();">
<mx:Script>
<![CDATA[
import fbAPI;
public function startGame():void {
var fbAPI:fbAPI = new fbAPI(); // breaks on this line
fbAPI.fbLogin();
}
]]>
</mx:Script>
</mx:Application>
And here is my fbAPI.as stub that doesn't seem to get imported:
package {
public class fbAPI {
import mx.controls.Alert;
public function fbLogin():void {
Alert.show('test');
}
}
}
Try putting your import statements above your class and also just rename the instance name of the fbapi in your mxml real quick.
Edit: nevermind, I forgot in AS3 you don't need a constructor.
Make sure you put the fbAPI.as file in the same location as your mxml file.