I want to create a class that handles Flash-PHP client-server communication. Basically, Flash sends (eg after clicking a button in my UI) a variable to PHP and PHP in turn sends a value to Flash.
The class could be similar to the following:
package
{
import flash.net.URLLoader;
import flash.net.URLVariables;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.events.Event;
import flash.events.IOErrorEvent;
//
public class CSManager extends MovieClip
{
//
var scriptLoader:URLLoader;
//
public function CSManager()
{
scriptLoader = new URLLoader();
scriptLoader.addEventListener(Event.COMPLETE, handleLoadSuccessful);
scriptLoader.addEventListener(IOErrorEvent.IO_ERROR, handleLoadError);
}
//;
public function handleLoadSuccessful($evt:Event):void
{
trace("Message sent.");
}
//
public function handleLoadError($evt:IOErrorEvent):void
{
trace("Message failed.");
}
//
public function sendLoad(variable):void
{
var scriptRequest:URLRequest = new URLRequest("http://mydomain/myapp/my.php");
var scriptVars:URLVariables = new URLVariables();
scriptVars.var1 = variable;
scriptRequest.method = URLRequestMethod.POST;
scriptRequest.data = scriptVars;
scriptLoader.load(scriptRequest);
}
}
}
So, I imagine that in the body of the method called by the button I instantiate this class and call the CSManager sendLoad method.
As you can see, sendLoad sends data to the server and two methods handle the result.
When data is received the app should parse the result and update a view but I want to leave this class decoupled from the parser and from the class that updates the view, and use it only to retrieve data from the server.
This specifically means I don’t want to parse the data and update the view from inside the body of the handleLoadSuccessful method but I want to find a different solution.
Which could be a good approach to solve this problem?
Edit: I found a better piece of code, but it seems the problem here is the same.
Dispatch an event. This is one effective technique to decouple your code.
Your class extends MovieClip, and MovieClip extends Sprite which extends InteractiveObject which extends EventDispatcher. This means that your object is an EventDispatcher and thus can dispatch an event thusly:
In the code that is using this class, you would listen to the event like this:
also you’d need the constant string
defined somewhere sensible (like as static class property of the CSManager)
Just to clarify, I am not suggesting you call your event MYEVENT, you can change that to something more meaningful like STRAWBERRIES_AND_CREAM or whatever makes sense in your specific context.