Best class design to Send XML and Receive Response in Flash - actionscript-3

I would like to send an XML message, and receive a response from a server and decode it.
That's my class design approach, I would like to know the best design for that thing.
class XMLRequest extends EventDispatcher
{
private var m_data:XML;
private var m_xmlString:String;
public function XMLRequest(){ m_data = null;}
public function setRequest(xmlString:String):Boolean
{
if(xmlString)
{
m_data = new XML(xmlString);
trace("Request --" + m_xmlString);
return true;
}
return false;
}
}
class XMLResponse extends EventDispatcher
{
private m_xmlString:String;
public function XMLResponse(){ m_data = null;}
public function getResponse(data:XML):String
{
if(data)
{
m_xmlString = data.toString();
trace("Repsonse --" + m_xmlString);
return m_xmlString;
}
return " ";
}
then I will have a class Client, that sends and receives the response.
Is that a good approach or not ?

I recommend use class disign like adobe Loader. Also, I recommend use native class XML instead of String
XMLLoader.as
package {
import flash.events.IEventDispatcher;
[Event(type="flash.events.Event", name="complete")]
public interface XMLLoader extends IEventDispatcher {
function load(requestXML:XML):void;
function getResponseXML():XML;
}
}
XMLLoaderTester.as
package {
import flash.display.Sprite;
import flash.events.Event;
public class XMLLoaderTester extends Sprite {
public function XMLLoaderTester() {
var loader:XMLLoader; //dont forget instantiate
loader.addEventListener(Event.COMPLETE, onResponse);
var requestXML:XML = <command>getData</command>;
loader.load(requestXML);
}
private function onResponse(event:Event):void {
var loader:XMLLoader = XMLLoader(event.target);
trace(loader.getResponseXML());
}
}
}

Related

Accessing object parameters from another object actionscript3

in the following video:
http://tv.adobe.com/watch/actionscript-11-with-doug-winnie/communicating-between-classes-episode-52/
he have two instances of object communicating together, both objects were created from Flash profession, and they simply "talk" by using the dot notation.
my program creates the objects dynamically, how can I communicate from one class to another from within the created instances? the creation may be from the main .as file or from within an object created from Main,
is this even possible?
If you can't keep object reference, you may need a third class to be the bridge between the objects.
Here is an example
public class NotifyMgr
{
private static var _instance:NotifyMgr = new NotifyMgr();
public static function getInstance():NotifyMgr
{
return _instance;
}
//send a message
public function sendMessage(msgType:String, data:*):void
{
var observers:Vector.<IObserver> = notifies[msgType] as Vector.<IObserver>;
if (observers == null)
{
return;
}
for each (var obj:IObserver in observers)
{
obj.notify(msgType, data);
}
}
private var notifies:Dictionary = new Dictionary();
//regiter a observer by msgType
public function register(msgType:String, obj:IObsever):void
{
if (notifies[msgType] == null)
{
notifies[msgType] = new Vector.<IObserver>();
}
var observers:Vector.<IObserver> = notifies[msgType] as Vector.<IObserver>;
if (obj != null && observers.indexOf(obj) == -1)
{
observers.push(obj);
}
}
public function unRegister(msgType:String, obj:IObserver):void
{
}
}
/**
*Your object should implement this interface
*/
public interface IObserver
{
function notify(msgType:String, data:*):void;
}
So you could create object A and b that both implement interface IObserver, and register A in NotifyMgr, call NotifyMgr.sendMessage in B,then A will know it.
In this example, Main is your Document Class, and Die is an extension of the Sprite Class. You can call its rollDie() method from within the Main Class because the access modifier is set to public
package{
import flash.display.Sprite;
import flash.events.MouseEvent;
public class Main extends Sprite{
public var die:Die;
public function Main()
{
//create a die
this.die = new Die();
addChild(die);
var button:MovieClip = new MovieClip();
addChild(button);
button.addEventListener(MouseEvent.CLICK, onButtonClick);
}
private function onButtonClick(e:MouseEvent):void
{
this.die.rollDie();
}
}
/**
* Die inherits from Sprite
*/
public class Die extends Sprite {
public function Die() {}
public function rollDie():void
{
var result:int = Math.ceil( Math.random()*6 );
trace("rolling die: " + result);
}
}
}

as3 calling a function in Main.as Document Class from another class

I am sure this is a popular question but I can't find the exact answer I need. I simply need to access a function or functions created in the Main.as document class. I have tried several methods and they do not seem to work. Here is one example I tried.
anotherClass.as // This needs to access functions Main.as
package com
{
import Main;
public class anotherClass
{
private var stageMain:Main;
public function anotherClass()
{
// tries to call a function in Main.as called languageLoaded. NO WORK!
stageMain.languageLoaded("English");
// in the Main.as languageLoaded is a public function
}
}
}
The cleaner way is to simply pass a reference to Main to the constructor of the class you want to be able to access it.
For example, your AnotherClass could look like this:
class AnotherClass
{
private var _main:Main;
public function AnotherClass(main:Main)
{
_main = main;
_main.test(); // Success!
}
}
And your main class:
class Main
{
public function Main()
{
var another:AnotherClass = new AnotherClass(this);
}
public function test():void
{
trace("Success!");
}
}
public class MainDoc extends MovieClip // as long as it extends eventDispatcher you re fine
{
private var otherClass:OtherClass;
public function MainDoc()
{
otherClass = new OtherClass();
otherClass.addEventListener("otherClassCustomEvent", onOtherClassReady);
otherClass.startLogic();
}
public function onOtherClassReady(event:Event = null)
{
trace("from other class:", otherClass.infoToShare) // traces "from other class: YOLO!"
}
}
public class OtherClass extends EventDispatcher // must extend the event dispatcher at least
{
public var infoToShare:String;
public function OtherClass()
{
}
public function startLogic()
{
// do what you got to do
// when you have your data ready
infoToShare = "YOLO!";
dispatchEvent("otherClassCustomEvent");
}
}
Once you're confortable with that, you can start looking into building custom events that could carry the variable to send back
Ok I got the following code to work. It's really a messy solution but I didn't know of a better way. It works. I just hope it's stable and does not use a lot of resources.
If you have a much better Idea I am open.
Here is the MainDoc.as
package {
import flash.display.MovieClip;
import flash.events.*;
import com.*;
import com.views.*;
import flash.display.*;
import flash.filesystem.*;
import com.greensock.*;
import com.greensock.easing.*;
import flash.system.System;
public class mainDoc extends MovieClip
{
/// (Get Main Doc flow) this creates an instace of the main timeline
/// and then I send it
private static var _instance:mainDoc;
public static function get instance():mainDoc { return _instance; }
/// Calls the defaultVars.as in to "vars".
var vars:defaultVars = new defaultVars();
public function mainDoc()
{
/// Makes this class ready to be passed to defautVars.as
_instance = this;
// Sends the _instance to defaulVars.as to be accessed later.
vars.getMainDoc(_instance);
// Calls a function in defaultVars.as and loads a var
vars.loadButtonVars("English");
}
}
}
Here is the defaultVars.as
package com {
import flash.display.Stage;
import flash.events.*
import flash.net.*;
import flash.display.*;
import flash.filesystem.*;
public class defaultVars
{
/// Makes the MainDoc.as a MovieClip
// Not sure if this is good but it works.
public var MainDoc:MovieClip;
public function defaultVars()
{
}
public function getMainDoc(_instance:MovieClip)
{
trace("CALLED" + _instance);
/// receives the _instance var and its converted to a MovieClip
// This can now be used in any function because I declared it a public var.
MainDoc = _instance;
}
public function loadButtonVars(Language:String)
{
myLoader.load(new URLRequest("Languages/" + Language + "/vars.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void
{
myXML = new XML(e.target.data);
/// Home Screen Buttons
homeT = myXML.Button.(#Title=="homeT");
homeB1 = myXML.Button.(#Title=="homeB1");
homeB2 = myXML.Button.(#Title=="homeB2");
homeB3 = myXML.Button.(#Title=="homeB3");
homeB4 = myXML.Button.(#Title=="homeB4");
homeB5 = myXML.Button.(#Title=="homeB5");
/// HERE IS WHERE I CALL FUNCTION from MainDoc after xml is loaded.
/////////////////
trace("xml loaded!!!! " + homeB1);
MainDoc.languageLoaded(Language);
}
}
}
}

Facebook abobe as3 api for air for mobile

I am planing a project that involves a cross platform (Android and I.O.S) mobile app that logs in using Facebook. I have no experience with the face book API and cant find any use full material for newbies. I want to use air for its cross platform capabilities so want to avoid multiple solutions for each platform. I have done many searches for help but haven't found much. Can any of you point me to resources you found use full starting off with this sort of thing.
The AS3 Facebook API is all you need. ( http://code.google.com/p/facebook-actionscript-api/ ) Maybe you will have to change a few things (like the JSON methods in there) but otherwise it seems to work alright. You can download several examples from there as well, you can see the usage for different types of environment.
Also, read this article from Tom Krcha http://www.adobe.com/devnet/games/articles/getting-started-with-facebooksdk-actionscript3.html
If you have more specific questions, ask. This one is too generic.
EDIT:
Here is a class I wrote some time ago for a small project
package com.company.social {
import com.facebook.graph.FacebookMobile;
import com.company.AppConst;
import com.company.IDestroyable;
import com.company.Main;
import com.company.displayassets.WebViewCloseStripe;
import com.company.events.FacebookControllerEvent;
import com.company.events.TwitterControllerEvent;
import flash.display.BitmapData;
import flash.display.PNGEncoderOptions;
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.EventDispatcher;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import flash.media.StageWebView;
import flash.utils.ByteArray;
import flash.utils.clearTimeout;
import flash.utils.setTimeout;
public class FacebookController extends EventDispatcher implements IDestroyable {
private static const APP_ID:String = "1234512345"; // Your App ID.
private static const SITE_URL:String = "some_url";
//Extended permission to access other parts of the user's profile that may be private, or if your application needs to publish content to Facebook on a user's behalf.
private var _extendedPermissions:Array = ["publish_stream","user_website","user_status","user_about_me"];
private var _stage:Stage;
private var _webView:StageWebView;
private var _topStripe:WebViewCloseStripe;
private var _activity:String;
private var _timeoutID:uint;
public static const ACTIVITY_LOGIN:String = "login";
public static const ACTIVITY_POST:String = "post";
public function FacebookController(stage:Stage) {
_stage = stage;
init();
}
private function init():void {
_activity = ACTIVITY_LOGIN;
startTimeout();
FacebookMobile.init(APP_ID, onHandleInit, null);
}
private function onHandleInit(response:Object, fail:Object):void {
if (response) {
stopTimeout();
dispatchEvent(new FacebookControllerEvent(FacebookControllerEvent.LOGIN_COMPLETE));
//FacebookMobile.api("/me", handleUserInfo);
}
else {
/*trace("no response, login -->");
for(var prop in fail["error"]) {
trace(prop+": "+fail["error"][prop]);
}*/
loginUser();
}
}
private function startTimeout():void {
trace("timeout start");
clearTimeout(_timeoutID);
_timeoutID = setTimeout(timeout, AppConst.TIMEOUT_TIME);
}
private function timeout():void {
trace("timed out");
clearTimeout(_timeoutID);
dispatchEvent(new FacebookControllerEvent(FacebookControllerEvent.TIMEOUT));
}
private function stopTimeout():void {
trace("timeout stop");
clearTimeout(_timeoutID);
}
private function loginUser():void {
stopTimeout();
_topStripe = new WebViewCloseStripe();
_topStripe.getCloseButton().addEventListener(MouseEvent.CLICK, closeClickHandler);
_stage.addChild(_topStripe);
_webView = new StageWebView();
_webView.viewPort = new Rectangle(0, _topStripe.height, _stage.fullScreenWidth, _stage.fullScreenHeight - _topStripe.height);
FacebookMobile.login(handleLogin, _stage, _extendedPermissions, _webView);
}
private function handleLogin(response:Object, fail:Object):void {
if(_topStripe) {
_topStripe.getCloseButton().removeEventListener(MouseEvent.CLICK, closeClickHandler);
_topStripe.destroy();
_stage.removeChild(_topStripe);
_topStripe = null;
}
if(_webView) {
_webView = null;
}
if(response) {
dispatchEvent(new FacebookControllerEvent(FacebookControllerEvent.LOGIN_COMPLETE));
//FacebookMobile.api('/me', handleUserInfo);
}
else {
dispatchEvent(new FacebookControllerEvent(FacebookControllerEvent.LOGIN_ERROR));
}
}
private function closeClickHandler(e:MouseEvent):void {
dispatchEvent(new FacebookControllerEvent(FacebookControllerEvent.CLOSE));
}
private function handleUserInfo(response:Object, fail:Object):void {
if (response) {
for(var prop in response) {
trace(prop+": "+response[prop]);
}
}
}
private function handleUploadImage(result:Object, fail:Object):void {
stopTimeout();
if(result) {
dispatchEvent(new FacebookControllerEvent(FacebookControllerEvent.POST_COMPLETE));
}
else {
dispatchEvent(new FacebookControllerEvent(FacebookControllerEvent.POST_ERROR));
}
}
public function postWithImage(message:String, imageData:BitmapData):void {
_activity = ACTIVITY_POST;
var byteArray:ByteArray = imageData.encode(new Rectangle(0, 0, imageData.width, imageData.height), new PNGEncoderOptions());
var params: Object = new Object;
params.image = byteArray;
params.fileName = "image.png";
params.message = message;
startTimeout();
FacebookMobile.api("/me/photos", handleUploadImage, params, "POST");
}
public function reset():void {
FacebookMobile.logout(handleReset, SITE_URL);
}
public function handleReset(response:Object):void {
dispatchEvent(new FacebookControllerEvent(FacebookControllerEvent.RESET));
}
public function destroy():void {
if(_webView) {
_webView.dispose();
_webView = null;
}
if(_topStripe) {
_topStripe.getCloseButton().removeEventListener(MouseEvent.CLICK, closeClickHandler);
_topStripe.destroy();
_stage.removeChild(_topStripe);
_topStripe = null;
}
_stage = null;
}
}
}
Alternatively you can use a native extension like this:
http://www.milkmangames.com/blog/tools/#iosgv
There are free versions from other publishers available as well.

In ActionScript 3.0, can you use addEventListener for one class to react to the function call of another class?

I know how to use addEventListener for one class to react to another class's button being clicked on. What if you want to use it for a more general purpose than that? What if you want to use it to react to one of the member functions of the other class being called? Is there a syntax for that? Thanks!
Edit: Please note that I have already Googled for the answer.
If you want to listen for another class' member function call, you need that function call to dispatch an Event. This is as simple as...
Listener Class
addEventListener("customEvent", listenerFunc);
Dispatcher Class (extends EventDispatcher / implements IEventDispatcher)
dispatchEvent(new Event("customEvent"));
As long as the listener class is above the dispatcher class in the object hierarchy, this will work perfectly. If not, you may want to use some sort of Global EventDispatcher class and register all listeners on that.
You can create your own events and dispatch them from the other class and listen to them in your listening class. Here is some code
In class A (assuming it inherits EventDispatcher)
public function classAMethod():void
{
dispatchEvent(new Event("someCustomTypeForEvent"));
}
In class B (assuming it has a reference to Class A)
public function classBMethod():void
{
classA.addEventListener("someCustomTypeForEvent",customHandler);
}
public function customHandler(e:Event):void
{
trace("handle event");
}
It's like in JAVA for java.awt.Component instances and all Objects that extends java.awt.Component; in AS3 you may add Listeners to all Objects that extends flash.display.Sprite instances which implements methods of IEventDispatcher for you...
So, If you have a class which do not extends flash.display.Sprite, you'll have to extend EventDispatcher in order to add Listeners to your instances and handle Events...
If the class may not extend EventDispatcher, you'll have to implement the IEventDispatcher.
Here is a [class MainClass] that extends [class MovieClip]
This MainClass instance, creates :
An instance of [class ObjectA] which extends [class Object] and implements IEventDispatcher,
An instance of [class ObjectB] which extends [class EventDispatcher]
Here is the code that use the extension method and the implementation method :
I hope this quick done example will help you...
(And sorry for my English, this is not my native language.)
in MainClass.as :
package com
{
import flash.utils.getDefinitionByName;
import flash.display.MovieClip;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
import flash.utils.getQualifiedSuperclassName;
import com.classes.ObjectA;
import com.classes.ObjectB;
import flash.events.Event;
public class MainClass extends flash.display.MovieClip
{
private static const DEBUG:Boolean = true;
private static var instance:MainClass;
private static var instanceOfA:ObjectA;
private static var instanceOfB:ObjectB;
public function MainClass()
{
MainClass.debug("MainClass constructor called");
MainClass.debug(getClassInformations(MainClass));
MainClass.debug(getClassInformations(ObjectA));
MainClass.debug(getClassInformations(ObjectB));
instanceOfA = new ObjectA();
instanceOfB = new ObjectB();
instanceOfA.addEventListener(ObjectA.DO_SOMETHING_EVENT,onInstanceOfA_doSomething,false,0,false);
instanceOfB.addEventListener(ObjectB.DO_SOMETHING_EVENT,onInstanceOfB_doSomething,false,0,false);
instanceOfA.doSomething();
instanceOfB.doSomething();
}
public static function onInstanceOfA_doSomething(e:Event):void
{
trace("An ObjectA has Dispatched An Event of type \"" + e.type + "\"" + " on " + e.target);
}
public static function onInstanceOfB_doSomething(e:Event):void
{
trace("An ObjectB has Dispatched An Event of type \"" + e.type + "\"" + " on " + e.target);
}
public static function getDebugMode():Boolean
{
return DEBUG;
}
public static function debug(string:String)
{
if (getDebugMode())
{
trace(string);
}
}
public static function getClassInformations(someClass:Class):String
{
var clss:Object = null;
var supClss:Object = null;
clss = getDefinitionByName(getQualifiedClassName(someClass));
try
{
supClss = getDefinitionByName(getQualifiedSuperclassName(someClass));
}
catch (e:ArgumentError)
{
// Has no superClass (ex:Object)
}
if (supClss != null)
{
return ("class " + clss + " extends " + supClss);
}
else
{
return ("class " + clss);
}
}
}
}
in ObjectB.as (simplest way):
package com.classes{
import com.MainClass;
import flash.events.EventDispatcher;
import flash.events.Event;
public class ObjectB extends EventDispatcher {
public static var DO_SOMETHING_EVENT:String = "do_something_event";
private var onDoSomethingEvent:Event = new Event(DO_SOMETHING_EVENT,false,false);
public function ObjectB() {
MainClass.debug("constructor ObjectB called");
}
public function doSomething():void{
this.dispatchEvent(onDoSomethingEvent);
}
}
}
in ObjectA.as (there you must implement all the methods of the interface IEventDispatcher):
package com.classes
{
import com.MainClass;
import flash.events.IEventDispatcher;
import flash.events.EventDispatcher;
import flash.events.Event;
public class ObjectA implements IEventDispatcher
{
public static var DO_SOMETHING_EVENT:String = "do_something_event";
private var onDoSomethingEvent:Event = new Event(DO_SOMETHING_EVENT,false,false);
private var dispatcher:EventDispatcher;
public function ObjectA()
{
dispatcher = new EventDispatcher(this);
MainClass.debug("constructor ObjectA called");
}
public function doSomething():void
{
this.dispatchEvent(onDoSomethingEvent);
}
public function addEventListener(
event_type:String,
event_listener:Function,
use_capture:Boolean = false,
priority:int = 0,
weakRef:Boolean = false
):void
{
// implements addEventListener here
dispatcher.addEventListener(event_type, event_listener, use_capture, priority, weakRef);
}
public function dispatchEvent(e:Event):Boolean
{
// implements dispatchEvent here
return dispatcher.dispatchEvent(e);
}
public function removeEventListener(
event_type:String,
event_listener:Function,
use_capture:Boolean = false
):void
{
// implements removeEventListener here
dispatcher.removeEventListener(event_type, event_listener, use_capture);
}
public function hasEventListener(type:String):Boolean
{
// implements hasEventListener here
return dispatcher.hasEventListener(type);
}
public function willTrigger(type:String):Boolean
{
// implements willTrigger here
return dispatcher.willTrigger(type);
}
}
}
Note that if you extend an EventDispatcher, you may also want to override some methods.
In this case, you must use the "override keyword as :
public override function dispatchEvent (e:Event):Boolean {
// a method of EventDispatcher may be overridden if needed !
// do what you need HERE...
return dispatchEvent(e);
}
In AS3 you must specify the override keyword or you'll get an Error 1024:
"Overriding a function that is not marked for override."
When you create a new EventDispatcher through implement or extend, you may also specify additional arguments and methods to this object as:
public function ListenerObject (v:View,m:Main) {
dispatcher = new EventDispatcher(this);
view = v;
master = m;
}
public function getView ():View {
return view;
}
public function getMain ():Main {
return master;
}
then use those methods in the callback method as :
public function callback(e:Event):void{
e.target.getView ();
//...
}

Need help understand MVC implementation within Actionscript 3 AS3, please

I am learning MVC implementation with ActionScript 3.0. So far, I have done alright but have couple of questions that can make this learning process very pleasant for me. I would highly appreciate your help and wisdom.
Let me explain how I am implementing a simple MVC implementation:
My Flash Movie is called FusionMVC. I have all the MVC files within the same package like this:
DataModel
DataControl
DataView
Application Facade
Here are my question:
As I understand it correctly, whenever I need to place a display object on the main stage, I declare or implement that display object in DataView class, am I right?
I have a symbol/display object called "Box" in the main library. I add this symbol to the stage by instantiating it within DataView class which I am able to see at runtime. Now if I need to add an EventListener called "ClickHandler" to this object:
Where do I declare this "ClickHandler" event, please? I am currently declaring it in the DataModel Class.
What I am confused about is to where to declare the EventHandler Methods. DataModel, or DataControl?
Thank you for your help. Here is the entire code:
//DATAMODEL
package
{
import flash.events.*;
import flash.errors.*;
public class DataModel extends EventDispatcher
{
public static const UPDATE:String = "modelUpdaed";
private var _txt:String;
public function DataModel()
{
}
public function get Text():String
{
return _txt;
}
public function set Text(p:String):void
{
_txt = p;
notifyObserver();
trace("MODEL HAS BEEN CHANGED");
}
public function notifyObserver():void
{
dispatchEvent(new Event(DataModel.UPDATE));
}
public function sayHello(e:Event):void
{
trace("HEY HELLO");
}
}
}
//DATACONTROL
package
{
import flash.display.*;
import flash.events.*;
import flash.errors.*;
public class DataControl
{
private var _model:DataModel;
public function DataControl(m:DataModel)
{
_model = m;
}
}
}
//DATAVIEW
package
{
import flash.display.*;
import flash.events.*;
import flash.errors.*;
public class DataView extends Sprite
{
private var _model:DataModel;
private var _control:DataControl;
public var b:Box;
public function DataView(m:DataModel, c:DataControl)
{
_model = m;
_control = c;
addBox();
}
public function addBox():void
{
b = new Box();
b.x = b.y = 150;
//b.addEventListener(MouseEvent.CLICK, vHandler);
addChild(b);
}
}
}
//APPLICATION FACADE
package
{
import flash.display.*;
import flash.events.*;
import flash.errors.*;
public class Main extends Sprite
{
private var _model:DataModel;
private var _control:DataControl;
private var _view:DataView;
public function Main()
{
_model = new DataModel();
_control = new DataControl(_model);
_view = new DataView(_model, _control);
addChild(_view);
}
}
}
You are correct - display objects should handle events from their own children:
public function addBox():void
{
b = new Box();
b.x = b.y = 150;
b.addEventListener(MouseEvent.CLICK, boxClickHandler);
addChild(b);
}
Handle the event in the view:
private function boxClickHandler(event:MouseEvent)
{
_control.sayHello();
}
And then you just need to add to your controller the method to change the model:
public class DataControl
{
....
public function sayHello():void
{
_model.sayHello();
}