Flex 4: Accessing public method in main application from component - apache-flex

I need to be able to call a method from a component located under the main application in Flex 4. Can anyone tell me please how to do this without using FlexGlobals please?
Sample code is attached. Thanks in advance.
// TestApp.mxml (application)
<?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"
creationComplete="initApp()">
<fx:Script>
<![CDATA[
import com.TestComp;
import mx.managers.PopUpManager;
public function myMethod():void
{
// do something
}
protected function initApp():void
{
var popUp:TestComp = new TestComp();
PopUpManager.addPopUp(popUp, this, true);
}
]]>
</fx:Script>
</s:WindowedApplication>
// TestComp.mxml (component)
<?xml version="1.0" encoding="utf-8"?>
<s:Group 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="400" height="300">
<fx:Script>
<![CDATA[
private function doSomething(event:MouseEvent):void
{
// call to myMethod() in TestApp.mxml
}
]]>
</fx:Script>
<s:Button click="doSomething(event)" label="Click Me"/>
</s:Group>

This is bad design. You should provide a callback function or an event listener.
// TestComp.mxml
<mx:Metadata>
[Event(name="doSomethingEvent", type="flash.events.Event")]
</mx:Metadata>
<mx:Script><![CDATA[
private function doSomething(event:MouseEvent):void
{
this.dispatchEvent(new Event("doSomethingEvent"));
}
]]></mx:Script>
// TestApp.mxml
protected function initApp():void
{
var popUp:TestComp = new TestComp();
popUp.addEventListener("doSomethingEvent", myMethod);
PopUpManager.addPopUp(popUp, this, true);
}
private function myMethod(event: Event): void
{
// do something
}
And this is a callback example:
// TestComp.mxml
public var doSomethingCallback: Function;
private function doSomething(event:MouseEvent):void
{
doSomethingCallback.call();
}
// TestApp.mxml
protected function initApp():void
{
var popUp:TestComp = new TestComp();
popUp.doSomethingCallback = myMethod;
PopUpManager.addPopUp(popUp, this, true);
}
private function myMethod(): void
{
// do something
}

Easiest option?
Take out the click handler from the button in TestComp.
In your main app, add a listener to TestComp (if it's a direct child of the main application) or itself (if TestComp is further down the display list) for MouseEvent.CLICK. In the handler, test to see if the event's target is the TestComp either through == if you've got a direct reference, or through "is" if not.
That's the least amount of effort from what you have just now, still relies on (bubbling) events, and is more "correct"

I do agree with splash that it's bad design, but the following should work
//in TestApp
protected function initApp():void
{
var popUp:TestComp = new TestComp(this);
PopUpManager.addPopUp(popUp, this, true);
}
//in TestComp
private var app:TestApp;
public function TestComp(app:TestApp)
{
this.app = app;
}
private function doSomething(event:MouseEvent):void
{
// call to myMethod() in TestApp.mxml
app.myMethod();
}
or you could do it this way
//in TestApp
protected function initApp():void
{
var popUp:TestComp = new TestComp(this);
popUp.addEventListener( 'test' , eventListener );
PopUpManager.addPopUp(popUp, this, true);
}
private function eventListener(event:Event):void
{
//in which case myMethod doesn't need to be public
myMethod();
}
//in TestComp
private function doSomething(event:MouseEvent):void
{
dispatchEvent( new Event('test') );
}

Related

Red5 - Invoking client methods from application server doesn't work

how would you invoke a client flex method from application in red5-service-1.0.5-RELEASE appliocation .
and my jdk version is 1.8(64-bit).flex 4 ,as3
package org.red5.demos;
import org.red5.server.adapter.ApplicationAdapter;
import org.red5.server.api.IConnection;
import org.red5.server.api.scope.IScope;
import org.red5.server.api.service.IServiceCapableConnection;
import org.red5.server.api.stream.IServerStream;
/**
* #author user
*
*/
public class Application extends ApplicationAdapter {
private IScope appScope;
private IServerStream serverStream;
#Override
public boolean appStart(IScope app){
super.appStart(app);
System.out.println("hello demo start");
appScope=app;
return true;
}
#Override
public boolean appConnect(IConnection conn,Object[]obj){
IScope appScope=conn.getScope();
System.out.println("appConnect");
callient(conn); //appConnect and calling client method
return super.appConnect(conn, obj);
}
private void callient(IConnection conn){
if(conn instanceof IServiceCapableConnection){
System.out.println("connect to flash side");
((IServiceCapableConnection) conn).invoke("yourFunctionInFlash"); // involing client side method ,but print "connect to flash side"
}
}
//disconnected
#Override
public void appDisconnect(IConnection conn){
if(appScope==conn.getScope() && serverStream!=null){
serverStream.close();
}
super.appDisconnect(conn);
}
}
and my flex side code,in my demo ,,after connect to red5 server application ,the netStatus info is success.
<?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" creationComplete="windowedapplication1_creationCompleteHandler(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import mx.graphics.codec.JPEGEncoder;
private var cam:Camera;
private var netConnection:NetConnection;
private var netStream:NetStream;**strong text**
protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
{
netConnection=new NetConnection();
netConnection.client = { onBWDone: function():void{} };
netConnection.addEventListener(NetStatusEvent.NET_STATUS,connectionServerHandler);
netConnection.connect("rtmp://192.168.61.132/Hello","ssl");//connect to Hello App
}
public function sayHello(reponder:String):void{
trace(reponder+"from server side ");
}
public function yourFunctionInFlash():void{
trace("hello"); //get message from server side
}
private function connectionServerHandler(event:NetStatusEvent):void{
trace(event.info.code); //it work success
}
]]>
</fx:Script>
</s:WindowedApplication>
but now ,flex side yourFunctionInFlash()method doesn't work,and server side also print "connect to flash side"message?>>> is any other I have missed?
thank you a lot .
Method yourFunctionInFlash should be defined in netConnection.client object. In your case you should assign netConnection.client = this. Also call super.appConnect on back end before invoking client method.

I want to create a custom check box which toggles between label and image

I want to create a custom reusable component by extending a spark Button class so that it has a checkbox and a label which says Show Image. When checkbox is selected an image will be displayed instead of the label. The Image path should be exposed as an API. How can we extend spark.components.Button to have it check box with labe or image (image path should be dynamic).
I tried to extend Button class as below but not sure how to create check box in it and how to pass image path as parameter to that.
package myClasses
{
import spark.components.Button;
public class ImageCheckBox extends Button
{
public function ImageButton()
{
super();
this.buttonMode = true;
}
}
}
I want to use the custom components something like below in application.
<myClasses:ImageCheckBox skinClass="mySkins.HelpButtonSkin" path="...."" label="Show Image" />
Something like this
package myClasses {
import flash.events.Event;
import spark.components.CheckBox;
import spark.components.Image;
import spark.components.Label;
import spark.components.supportClasses.SkinnableComponent;
public class ImageCheckBox extends SkinnableComponent {
[SkinPart(required=true)]
public var checkBox:CheckBox;
[SkinPart(required=true)]
public var labelComp:Label;
[SkinPart(required=true)]
public var image:Image;
private var pathChanged:Boolean = false;
private var _path:String;
public function get path():String {
return _path;
}
public function set path(value:String):void {
if (_path != value) {
_path = value;
pathChanged = true;
invalidateProperties();
}
}
private var labelChanged:Boolean = false;
private var _label:String;
public function get label():String {
return _label;
}
public function set label(value:String):void {
if (_label != value) {
_label = value;
labelChanged = true;
invalidateProperties();
}
}
public function ImageCheckBox() {
super();
setStyle("skinClass", ImageCheckBoxSkin);
}
override protected function partAdded(partName:String, instance:Object):void {
super.partAdded(partName, instance);
if (instance == checkBox) {
checkBox.addEventListener(Event.CHANGE, checkBoxChangeHandler)
}
else if (instance == labelComp) {
labelComp.text = label;
}
else if (instance == image) {
image.source = path;
}
}
override protected function partRemoved(partName:String, instance:Object):void {
super.partRemoved(partName, instance);
if (instance == checkBox) {
checkBox.removeEventListener(Event.CHANGE, checkBoxChangeHandler)
}
}
override protected function getCurrentSkinState():String {
return checkBox.selected ? "selected" : super.getCurrentSkinState();
}
override protected function commitProperties():void {
if (labelChanged) {
labelChanged = false;
labelComp.text = label;
}
if (pathChanged) {
pathChanged = false;
image.source = path;
}
super.commitProperties();
}
private function checkBoxChangeHandler(event:Event):void {
invalidateSkinState();
}
}}
And skin
<s:Skin xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:fb="http://ns.adobe.com/flashbuilder/2009"
xmlns:mx="library://ns.adobe.com/flex/mx">
<!-- host component -->
<fx:Metadata>
<![CDATA[
/**
* #copy spark.skins.spark.ApplicationSkin#hostComponent
*/
[HostComponent("myClasses.ImageCheckBox")]
]]>
</fx:Metadata>
<s:states>
<s:State name="normal"/>
<s:State name="selected"/>
</s:states>
<s:HGroup width="100%" height="100%" gap="3">
<s:CheckBox id="checkBox"
verticalCenter="0"
height="100%"/>
<s:Label id="labelComp"
verticalCenter="0" verticalAlign="middle"
width="100%" height="100%"
visible.normal="true" includeInLayout.normal="true"
visible.selected="false" includeInLayout.selected="false"/>
<s:Image id="image"
verticalCenter="0"
width="100%" height="100%"
fillMode="scale" scaleMode="letterbox"
visible.normal="false" includeInLayout.normal="false"
visible.selected="true" includeInLayout.selected="true"/>
</s:HGroup>

flex timer - appear disappare

I have an object in flex - which i want to appear upon a button clicked, disappear after 10 seconds or if the object is closed, and reappear if that same button pressed.
i've tried something like this:
public class my_obj
{
private var _myTimer: Timer;
public function my_obj()
{
_myTimer = new Timer(10000);
}
private function init(): void
{
_myTimer.addEventListener(TimerEvent.TIMER, onTimeout);
_myTimer.start();
}
private function onTimerTimeOut(event: TimerEvent): void
{
dispatchEvent(new Event(CLOSE_EVENT));
}
}
what am i missing?
Thanks!
Working fine. Here's the working code sample:
<?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">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<s:Panel width="100%" height="400" creationComplete="my_obj()">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
private var _myTimer: Timer;
public function my_obj():void
{
_myTimer = new Timer(10000);
}
private function init(): void
{
toggleBtn.visible = true;
_myTimer.addEventListener(TimerEvent.TIMER, onTimeout);
_myTimer.start();
}
private function onTimeout(event: TimerEvent): void
{
toggleBtn.visible = false;
//dispatchEvent(new Event(CLOSE_EVENT));
}
private function hideIt(): void
{
toggleBtn.visible = false;
}
]]>
</fx:Script>
<s:Button label="Some Button" click="init()"/>
<s:Button id="toggleBtn" label="Appeared on 'Some Button' click. Click to close it." click="hideIt()" visible="false"/>
</s:Panel>
</s:WindowedApplication>

Keyboard Application - Best way to have multiple buttons add letter to textinput? Use event handlers?

I'm working on an application and I am building a "Keyboard" component for it. There are 30 keys on the keyboard and it doesnt seem to make practical sense to create an event handler for each button. When the button is clicked, its label should be sent out to a function which adds it to a textinput field.
Should I just create a "click=SomeFunction(Button.label)" for each button or is there a better/faster/less processor intensive way to do it?
there is a much easier way. you can extend the button component and create a default click even that bubbles up. You then can have the parent component listening for the event. Here is a quick example:
myButton.mxml:
<?xml version="1.0" encoding="utf-8"?>
<mx:Button xmlns:mx="http://www.adobe.com/2006/mxml"
click="clickKeyHandler( event );">
<mx:Metadata>
[Event(name="keyboardClickEvent", type="com.KeyboardEvent")]
</mx:Metadata>
<mx:Script>
<![CDATA[
import com.KeyboardEvent;
protected function clickKeyHandler( event:MouseEvent ):void{
dispatchEvent( new KeyboardEvent( this.label ) );
}
]]>
</mx:Script>
</mx:Button>
com.KeyboardEvent:
package com
{
import flash.events.Event;
public class KeyboardEvent extends Event
{
public static const KEYBOARD_CLICK_EVENT:String = "keyboardClickEvent";
private var _value:String;
public function get value():String{
return _value;
}
public function KeyboardEvent( value:String = "" )
{
super( KEYBOARD_CLICK_EVENT, true );
_value = value;
}
override public function clone() : Event {
return new KeyboardEvent( _value );
}
}
}
usage in app:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute" creationComplete="initApp();" xmlns:local="*">
<mx:Script>
<![CDATA[
import com.KeyboardEvent;
private function initApp():void{
this.addEventListener( KeyboardEvent.KEYBOARD_CLICK_EVENT, keyboardHandler);
}
private function keyboardHandler( event:KeyboardEvent ):void{
trace( event.value );
}
]]>
</mx:Script>
<local:myButton label="1" />
<local:myButton label="2" />
<local:myButton label="3" />
<local:myButton label="4" />
</mx:Application>

Some [Bindable] properties in Flex work, some don't

Problem solved, see below
Question
I'm working in Flex Builder 3 and I have two ActionScript 3 classes (ABC and XYZ) and a Flex MXML project (main.mxml). I have an instance of XYZ as a property of ABC, and I want XYZ's properties to be visible ([Bindable]) in the Flex project in text controls.
Unfortunately, only prop3 and prop4 update when they are changed. I've entered the debugger to make sure that prop1 and prop2 change, but they are not being updated in the text controls.
Here's the code:
ABC.as
[Bindable]
public class ABC extends UIComponent {
/* Other properties */
public var xyz:XYZ = new XYZ();
/* Methods that update xyz */
}
XYZ.as
[Bindable]
public class XYZ extends Object {
private var _prop1:uint = 0;
private var _prop2:uint = 0;
private var _prop3:uint = 0;
private var _prop4:uint = 1;
public function get prop1():uint {
return _prop1;
}
public function set prop1(value:uint):void {
_prop1 = value;
}
/* getters and setters for prop2, prop3, and prop4 */
}
main.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:com="com.*" />
<com:ABC id="abc" />
<mx:Text text="{abc.xyz.prop1}" />
<mx:Text text="{abc.xyz.prop2}" />
<mx:Text text="{abc.xyz.prop3}" />
<mx:Text text="{abc.xyz.prop4}" />
</mx:Application>
Answer
It's not apparent from the small code snippets that I posted, but from within XYZ I was updating _prop3 and _prop4 using their setters. In constrast, I updated _prop1 and _prop2 through their private variables, not their setters. Thus, properties 1 and 2 were not dispatching update events.
It looks like your getters are returning voids. They should be returning uints, according to your field types.
Otherwise your code should be working fine. I've assembled and tested a working version with a Timer that sets all four values, so you can see all four updating:
Main.mxml:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local="*" creationComplete="onCreationComplete()">
<mx:Script>
<![CDATA[
private function onCreationComplete():void
{
var t:Timer = new Timer(1000);
t.addEventListener(TimerEvent.TIMER, t_tick);
t.start();
}
private function t_tick(event:TimerEvent):void
{
var i:uint = Timer(event.currentTarget).currentCount;
abc.xyz.prop1 = i;
abc.xyz.prop2 = i;
abc.xyz.prop3 = i;
abc.xyz.prop4 = i;
}
]]>
</mx:Script>
<local:ABC id="abc" />
<mx:VBox>
<mx:Text text="{abc.xyz.prop1}" />
<mx:Text text="{abc.xyz.prop2}" />
<mx:Text text="{abc.xyz.prop3}" />
<mx:Text text="{abc.xyz.prop4}" />
</mx:VBox>
</mx:Application>
ABC.as
package
{
import mx.core.UIComponent;
[Bindable]
public class ABC extends UIComponent
{
public var xyz:XYZ = new XYZ();
public function ABC()
{
super();
}
}
}
XYZ.as
package
{
[Bindable]
public class XYZ extends Object
{
private var _prop1:uint = 0;
private var _prop2:uint = 0;
private var _prop3:uint = 0;
private var _prop4:uint = 1;
public function XYZ()
{
super();
}
public function get prop1():uint {
return _prop1;
}
public function set prop1(value:uint):void {
_prop1 = value;
}
public function get prop2():uint {
return _prop2;
}
public function set prop2(value:uint):void {
_prop2 = value;
}
public function get prop3():uint {
return _prop3;
}
public function set prop3(value:uint):void {
_prop3 = value;
}
public function get prop4():uint {
return _prop4;
}
public function set prop4(value:uint):void {
_prop4 = value;
}
}
}
Have a look at those, plug things in and you should see it all come together. Post back if you have any questions. Cheers.
When you define your bindable sources through the use of getters and setters, the bindings don't seem to work. The solution is to declare a bindable event for your getter and dispatch the event in your setter:
[Bindable]
public class XYZ extends Object {
private var _prop1:uint = 0;
private var _prop2:uint = 0;
private var _prop3:uint = 0;
private var _prop4:uint = 1;
[Bindable(event="prop1Changed")]
public function get prop1():uint {
return _prop1;
}
public function set prop1(value:uint):void {
_prop1 = value;
dispatchEvent (new Event ("prop1Changed"));
}
/* getters and setters for prop2, prop3, and prop4 */
}
So whenever your private member changes, an event is dispatched that notifies any component linked to the getter that the property has changed.

Resources