Referencing textfield on stage issue - actionscript-3

I use this sample code taken from the docs: all the code is contained inside SocketExample.as, that is the DocumentClass too.
package {
import flash.display.Sprite;
public class SocketExample extends Sprite {
public function SocketExample() {
var socket:CustomSocket = new CustomSocket("127.0.0.1", 5000);
}
}
}
import flash.errors.*;
import flash.events.*;
import flash.net.Socket;
class CustomSocket extends Socket {
private var response:String;
public var txt:TextField;
public function CustomSocket(host:String = null, port:uint = 0) {
super();
configureListeners();
if (host && port) {
super.connect(host, port);
}
}
private function configureListeners():void {
addEventListener(Event.CLOSE, closeHandler);
addEventListener(Event.CONNECT, connectHandler);
addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
}
private function writeln(str:String):void {
str += "\n";
try {
writeUTFBytes(str);
}
catch(e:IOError) {
trace(e);
}
}
private function sendRequest():void {
trace("sendRequest");
response = "";
writeln("GET /");
flush();
}
private function readResponse():void {
var str:String = readUTFBytes(bytesAvailable);
response += str;
}
private function closeHandler(event:Event):void {
trace("closeHandler: " + event);
trace(response.toString());
}
private function connectHandler(event:Event):void {
trace("connectHandler: " + event);
sendRequest();
}
private function ioErrorHandler(event:IOErrorEvent):void {
trace("ioErrorHandler: " + event);
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
}
private function socketDataHandler(event:ProgressEvent):void {
trace("socketDataHandler: " + event);
readResponse();
}
public function returnResponse(){
return response.toString();
}
}
On socket close closeHandler gets called. How can I write the value of the response to a textfield on stage? I tried sending a custom Event from CustomSocket closeHandler but, even if I correctly added a listener to the constructor of SocketExample, I did not receive any event. What can I do?

Looks like you already added a public txt field for storing a reference to a text field. How about you create a text field in your SocketExample class, add it to the stage, and then set socket.txt = yourTextField. Then you can just use txt directly in closeHandler.

Related

as3 addEventListner on a function in another class

I have a class calling a function in another class. I want to know
if we can add an Event Listener to know if that function has fired and is finished etc.
Here is the section of the code that is relevant.
myMC = new pictures();
addChild(myMC);
myMC.loadImages("Joyful",1)
// Add Event Listener here to let me know loadImages was called and worked.
As you can see the function is called loadImages() and it is located in a class called pictures.as
Can I add an event listener to this?
Here is a new issue. I am using a similar method and I used your example below and it did not work. Am I missing an import or something? I am only showing the functions that pertain and not my whole script.
Main.class
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.display.*;
import flash.filesystem.*;
import com.greensock.*;
import com.greensock.easing.*;
import flash.system.System;
// Ed's Scripts
import com.*;
import com.views.*;
public class iRosaryMain extends MovieClip
{
/// (Get Main Doc flow) this creates an instace of the main timeline
/// and then I send it
private static var _instance:iRosaryMain;
public static function get instance():iRosaryMain
{
return _instance;
}
/// Declaring Vars
var audio:audioPrayers;
/// Loading Images
//public var theImages:pictures = new pictures();
/// Movie Clips
public var myMary:beautifulMary;
public var myMC:MovieClip;
public var myPic:MovieClip;
public var myFlags:MovieClip;
public static var mt:MovieClip;
var vars:defaultVars = new defaultVars();
public function iRosaryMain()
{
// (Get Main Doc flow) Here I send the an instacne of iRosaryMain to defaultVars.as
_instance = this;
vars.getMainDoc(_instance);
// Sets timeline to mt :) I hope
mt = _instance;
audio = new audioPrayers();
trace("Jesus I trust in you!");// constructor code
audio.sayHailMary();
if (stage)
{
init();
}
}
public function moveLanguages()
{
/// File to languages folder
var checkLanguageFolder:File = File.applicationStorageDirectory.resolvePath("Languages");
///// CHECK LANGUAGES FOLDER - if not in App Storage move it
if (! checkLanguageFolder.exists)
{
var sourceDir:File = File.applicationDirectory.resolvePath("Languages");
var resultDir:File = File.applicationStorageDirectory.resolvePath("Languages");
sourceDir.copyTo(resultDir, true);
trace( "Moved Language!");
}
}
//// MAIN FUNCTIONS IN iRosaryMainClass
function init()
{
//loadFlags();
moveLanguages();
//addChild(theImages);
intro();
}
public function loadFlags()
{
myFlags.addEventListener("MyEvent", eventHandler);
myFlags = new viewLanguages();
addChild(myFlags);
myFlags.x = stage.stageWidth / 2 - myFlags.getBounds(this).width / 2;
function eventHandler()
{
trace("yes loaded");
TweenMax.fromTo(myMary,3, {alpha:1}, {alpha:0, ease:Quint.easeOut, onComplete: closePic} );
}
}
function intro()
{
myMary = new beautifulMary();
addChild(myMary);
loadFlags();
}
public function closePic()
{
removeChild(myMary);
}
public function languageLoaded(lang:String)
{
trace("YES... " + lang);
homeIn();
}
public function homeIn()
{
if (myFlags)
{
TweenMax.fromTo(myFlags,1, {x:myFlags.x}, {x:0-myFlags.width, ease:Quint.easeInOut, onComplete:unloadMyFlags} );
}
function unloadMyFlags()
{
trace("Called Ease out");
if (myFlags is MovieClip)
{
//trace("CURRENT DISPLAY " + currentDisplayScreen);
trace("CURRENT mc " + myFlags);
removeChild(myFlags);
System.gc();
myFlags = null;
trace("CURRENT mc " + myFlags);
}
}
if (! myMC)
{
myMC = new viewHome();
myMC.name = "Home";
myMC.x = stage.stageWidth / 2 - myMC.width / 2;
addChild(myMC);
}
theEaseIn(myMC);
//Home.B1.addEventListener(MouseEvent.CLICK, theEaseOut(Home));
}
public function loadLanguage(Language:String):Function
{
return function(e:MouseEvent):void ;
{
trace("Did it work? " +Language);
vars.loadButtonVars(Language);;
};
//TweenMax.fromTo(EnglishButton,1, {x:EnglishButton.x}, {x:0-EnglishButton.width, ease:Quint.easeOut} );
}
public function loadView(screen:String)
{
trace("Received " + screen);
if (screen=="Home")
{
myMC = new viewHome();
addChild(myMC);
theEaseIn(myMC);
//Home.B1.addEventListener(MouseEvent.CLICK, theEaseOut(Home));
}
if (screen=="PrayTheRosary")
{
myMC = new viewPrayTheRosary();
addChild(myMC);
theEaseIn(myMC);
//Home.B1.addEventListener(MouseEvent.CLICK, theEaseOut(Home));
}
if (screen=="Options")
{
myMC = new viewOptions();
addChild(myMC);
theEaseIn(myMC);
}
if (screen=="Downloads")
{
myMC = new viewDownloads();
addChild(myMC);
theEaseIn(myMC);
}
if (screen=="beautifulMary")
{
myMC = new beautifulMary();
addChild(myMC);
theEaseIn(myMC);
}
if (screen=="Flags")
{
myFlags = new viewLanguages();
addChild(myFlags);
theEaseIn(myFlags);
}
if (screen=="Joyful" || screen=="Sorrowful" || screen=="Glorious" || screen=="Luminous")
{
myPic = new pictures();
addChild(myPic);
myPic.addEventListener( "ImagesLoaded", doTheEaseIn);
myPic.loadImages(""+screen+"",1);
function doTheEaseIn()
{
theEaseIn(myPic);
}
}
}
public function theEaseIn(mc:MovieClip)
{
if (myMC)
{
TweenMax.fromTo(mc,1, {x:stage.stageWidth+mc.width}, {x:stage.stageWidth/2 - mc.width/2, ease:Quint.easeInOut} );
}
}
public function theEaseOut(mc:MovieClip,nextMC:String):Function
{
return function(e:MouseEvent):void ;
{
loadView(nextMC);
/// Tweens out view on screen
TweenMax.fromTo(mc,1, {x:mc.x}, {x:0-mc.width, ease:Quint.easeInOut, onComplete:unloadMC} );
function unloadMC();
{
trace("Called Ease out");
if(mc is MovieClip);
{
//trace("CURRENT DISPLAY " + currentDisplayScreen);
trace("CURRENT mc " + mc);
removeChild(mc);
System.gc();
myMC = null;
trace("CURRENT mc " + mc);
};
};
};/// end return
}
////////////
}/// End iRosaryMain
}// End Package
viewLanguages.as
package com.views
package com.views
{
import flash.display.MovieClip;
import flash.filesystem.File;
import com.roundFlag;
import flash.events.*;
import flash.display.*;
public class viewLanguages extends MovieClip
{
var Flag:MovieClip;
//public static const FLAGS_LOADED:String = "flagsLoaded";
public function viewLanguages()
{
getLang();
}
function numCheck(num:int):Boolean
{
return (num % 2 != 0);
}
/// Get for App Opening
public function getLang()
{
/// When Live
var folderLanguages:File = File.applicationStorageDirectory.resolvePath("Languages");
var availLang = folderLanguages.getDirectoryListing();
var Lang = new Array();
var LangPath = new Array();
var fl:int = 0;
for (var i:uint = 0; i < availLang.length; i++)
{
if (availLang[i].isDirectory)
{
//flag = new Loader();
//flag.load(new URLRequest(File.applicationStorageDirectory.url + "Languages/" + Lang[i] + "/roundFlag.png"));
Lang.push(availLang[i].name);
LangPath.push(availLang[i].nativePath);
Flag = new roundFlag(availLang[i].name);
Flag.name = availLang[i].name;
if (numCheck(i)==false)
{
Flag.y = fl;
Flag.x = 0;
}
else
{
Flag.y = fl;
Flag.x = Flag.width + 33;
fl = fl + Flag.height + 33;
}
Flag.btext.text = availLang[i].name;
addChild(Flag);
trace(availLang[i].nativePath);// gets the name
trace(availLang[i].name);
}
}
trace("Get Lang Called");
dispatchEvent(new Event("MyEvent"));
}
}
}
Yes, you can. Considering you are adding your clip to the display list I assume it extends either Movieclip or Sprite, both of which extend EventDispatcher. In your pictures class you can simply use dispatchEvent(new Event("MyEvent"); to dispatch an event. Then you could add myMC.addEventListener("MyEvent", eventHandler); to react to it.
You should also not use strings for events like I wrote above. It would be better if you declared a public static const IMAGES_LOADED:String = "imagesLoaded"; in your pictures class. Then you should use this constant by dispatching and by listening to it.
EDIT: Here how it would look with the constant:
//your class
package {
import flash.events.Event;
import flash.display.Sprite;
public class Pictures extends Sprite {
public static const IMAGES_LOADED:String = "imagesLoaded";
public function Pictures() {
}
public function onAllImagesLoaded():void {
dispatchEvent(new Event(IMAGES_LOADED));
}
//rest of your methods
}
}
//you would call it like this:
var myMc:Pictures = new Pictures();
myMc.addEventListener(Pictures.IMAGES_LOADED, onImagesLoaded);
myMc.loadImages();
function onImagesLoaded(e:Event):void {
//...etc
}
You have to create custom event class for this to work. Like:
package com.some
{
import flash.events.Event;
public class SomeEvent extends Event
{
// Loading events
public static const MAINDATA_LOADING:String = "onMainDataLoading";
// Other event
public static const SOME_LOADING:String = "onSomeLoading";
public var params:Object;
public function SomeEvent($type:String, $params:Object, $bubbles:Boolean = false, $cancelable:Boolean = false)
{
super($type, $bubbles, $cancelable);
this.params = $params;
}
public override function clone():Event
{
return new SomeEvent(type, this.params, bubbles, cancelable);
}
}
}
Add event dispatch inside wanted class (Pictures) and pass wanted params to event (this or any else)
dispatchEvent(new SomeEvent(SomeEvent.IMAGES_LOADED, this));
Handle event listening:
var myMc:Pictures = new Pictures();
myMc.addEventListener(SomeEvent.IMAGES_LOADED, onImagesLoaded);
myMc.loadImages();
function onImagesLoaded(e:SomeEvent):void {
// handle event.
var picts:Pictures = (e.params as Pictures);
}

Actionscript : Going through .as with a variable

I got a variable
var Something = "Text";
i want to import Text .as that is placed in abc folder
so what can i do? I tried writing :
import abc.Something;
Doesn't work, any help?
Btw the main point again, i want to import Text
What you trying to do will not work. The import statement is for classes. You could define your text string in a static variable and then use this variable in your code. Be aware, this is not good design.
package abc{
public class TextHolder
{
public static var something:String = "Text";
}
}
in another class:
package {
import abc.TextHolder
public class Main
{
var text:String = TextHolder.something;
}
}
You could also use the include statement. With this statment you can include as files in to your current file
include "abc.script.as"
The variable in this script will then be included in the current script.
What you really want, I guess is to load text and other resources at runtime.
You can simply do that with the URL Loader.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLLoader.html
This example is from the adobe livedocs
package {
import flash.display.Sprite;
import flash.events.*;
import flash.net.*;
public class URLLoaderExample extends Sprite {
private loader:URLoader;
public function URLLoaderExample() {
loader = new URLLoader();
configureListeners(loader);
var request:URLRequest = new URLRequest("urlLoaderExample.txt");
try {
loader.load(request);
} catch (error:Error) {
trace("Unable to load requested document.");
}
}
private function configureListeners(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
dispatcher.addEventListener(Event.OPEN, openHandler);
dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}
private function completeHandler(event:Event):void {
var loader:URLLoader = URLLoader(event.target);
trace("completeHandler: " + loader.data);
var vars:URLVariables = new URLVariables(loader.data);
trace("The answer is " + vars.answer);
}
private function openHandler(event:Event):void {
trace("openHandler: " + event);
}
private function progressHandler(event:ProgressEvent):void {
trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
}
private function httpStatusHandler(event:HTTPStatusEvent):void {
trace("httpStatusHandler: " + event);
}
private function ioErrorHandler(event:IOErrorEvent):void {
trace("ioErrorHandler: " + event);
}
}
}
Its a little bit to much but covers the whole process of loading ascii data.

Facebook Actionscript and IE

I'm trying to use the Facebook Actionscript graph api but I seem to be having problems in IE (other browsers like chrome and firefox seem okay so far).
From what i can tell, it's logging in fine and returning the user id but when i do a lookup on that user with Facebook.api(_user, handleUserRequest); I get an error.
Is there any known problems with the Facebook Actionscript graph api that affects IE only?
thanks
ob
Per request - the error is as follows:
[IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2032: Stream Error. URL: https://graph.facebook.com/100002210990429?access%5Ftoken=205690086123032%7C2%2EUzvN3mFr07kPAecZ7qN1Rg%5F%5F%2E3600%2E1303135200%2E1%2D100002210990429%7Cz9L%5Fc26QKCc6cs2g5FClG%5FBsoZg"]
This if this url is pasted into chrome it works just fine, but IE returns 'unable to download XXXXXXXX from graph.facebook.com'
best
obie
the code that I'm using is as follows:
package com.client.facebookgame.services
{
import com.client.facebookgame.services.events.FacebookServiceEvent;
import com.facebook.graph.data.FacebookSession;
import com.facebook.graph.Facebook;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import flash.external.ExternalInterface;
import flash.net.URLRequestMethod;
import flash.utils.Timer;
import uk.co.thereceptacle.utils.Debug;
/**
* Facebook Service
*/
public class FacebookService extends EventDispatcher
{
// constants
public static const API_KEY : String = "XXXXXX";
public static const PERMISSIONS : String = "read_stream,publish_stream,user_likes";
public static const FB_REDIRECT_URL : String = "http://apps.facebook.com/appname/";
public static const LOGGED_IN : String = "loggedin";
public static const LOGGED_IN_ON_FB : String = "loggedinonfacebook";
public static const LOGGED_OUT : String = "loggedout";
public static const LOGGED_OUT_ON_FB : String = "loggedoutonfacebook";
public static const TIMEOUT_COUNT : int = 10;
public static const TIMER_DELAY : int = 3 * 1000;
// properties
private var _user : String;
private var _topUrl : String;
private var _currentState : String;
private var _timer : Timer;
private var _timerCount : int;
public var postObject : Object;
// constuctor
public function FacebookService()
{
if (ExternalInterface.available) _topUrl = ExternalInterface.call("top.location.toString");
Debug.log("facebook init", this);
Facebook.init(API_KEY, handleLogin);
startTiming();
currentState = _topUrl ? LOGGED_OUT : LOGGED_OUT_ON_FB;
}
// methods
public function login():void
{
Facebook.login(handleLogin, { perms: PERMISSIONS } );
}
public function logout():void
{
Facebook.logout(handleLogout);
}
public function selectUserFriendsWithAppRequestDialogue(message:String, dialogueType:String = "iframe", optionalPostObject:Object = null):void
{
this.postObject = optionalPostObject;
Facebook.ui("apprequests", { message:message }, handleAppRequest, dialogueType);
}
public function checkIfUserLikesApp():void
{
Facebook.api(_user + "/likes", handleLikes);
}
private function startTiming():void
{
if (_timer) clearTimer();
_timer = new Timer(TIMER_DELAY, TIMEOUT_COUNT);
_timer.addEventListener(TimerEvent.TIMER, handleTimerEvents);
_timer.addEventListener(TimerEvent.TIMER_COMPLETE, handleTimerEvents);
_timer.start();
}
private function clearTimer():void
{
_timer.stop();
_timer.removeEventListener(TimerEvent.TIMER, handleTimerEvents);
_timer.removeEventListener(TimerEvent.TIMER_COMPLETE, handleTimerEvents);
_timer = null;
_timerCount = 0;
}
// event handlers
private function handleLogin(success:Object, fail:Object):void
{
if (_timer) clearTimer();
if (success)
{
Debug.log(success, this);
_user = success.uid;
currentState = _topUrl ? LOGGED_IN : LOGGED_IN_ON_FB;
Facebook.api("/" + _user, handleGetUser);
}
else if (!success && !_topUrl)
{
ExternalInterface.call("redirect", API_KEY, PERMISSIONS, FB_REDIRECT_URL);
}
}
private function handleGetUser(success:Object, fail:Object):void
{
Debug.log(success + ", " + fail, this);
if (success) dispatchEvent(new FacebookServiceEvent(FacebookServiceEvent.GET_USER_COMPLETE, success));
else dispatchEvent(new FacebookServiceEvent(FacebookServiceEvent.GET_USER_FAIL, fail, true));
}
private function handleAppRequest(result:Object):void
{
if (postObject)
{
for (var i:int = 0; i < result.request_ids.length; i++)
{
var requestID:String = result.request_ids[i];
Facebook.api("/" + requestID, handleRequestFriends);
}
}
}
private function handleRequestFriends(success:Object, fail:Object):void
{
if (success)
{
var friendID:String = success.to.id;
Facebook.api("/" + friendID + "/feed", handleSubmitFeed, postObject, URLRequestMethod.POST);
}
else
{
Debug.log(fail, this);
}
}
private function handleLikes(success:Object, fail:Object):void
{
if (success)
{
for (var i:int = 0; i < success.length; i++)
{
Debug.log("compare " + success[i].id + " with key: " + API_KEY, this);
if (success[i].id == API_KEY)
{
Debug.log("found that user liked this app!!!", this, true);
dispatchEvent(new FacebookServiceEvent(FacebookServiceEvent.USER_LIKES_APP, { userLikesApp:true } ));
return;
}
}
dispatchEvent(new FacebookServiceEvent(FacebookServiceEvent.USER_LIKES_APP, { userLikesApp:false } ));
}
else
{
Debug.log(fail, this, true);
}
}
private function handleLogout(obj:*):void
{
currentState = _topUrl ? LOGGED_OUT : LOGGED_OUT_ON_FB;
}
private function handleSubmitFeed(success:Object, fail:Object):void
{
if (success) dispatchEvent(new FacebookServiceEvent(FacebookServiceEvent.FEED_SUBMITTED, success));
else dispatchEvent(new FacebookServiceEvent(FacebookServiceEvent.FEED_FAIL, fail, true));
}
private function handleTimerEvents(e:TimerEvent):void
{
switch (e.type)
{
case TimerEvent.TIMER :
_timerCount ++;
Debug.log("facebook init attempt " + _timerCount, this);
Facebook.init(API_KEY, handleLogin);
break;
case TimerEvent.TIMER_COMPLETE :
clearTimer();
dispatchEvent(new FacebookServiceEvent(FacebookServiceEvent.GET_USER_FAIL));
break;
}
}
// accessors / mutators
public function get currentState():String { return _currentState; }
public function set currentState(value:String):void
{
if (_currentState != value)
{
_currentState = value;
dispatchEvent(new FacebookServiceEvent(FacebookServiceEvent.STATE_UPDATE));
}
}
}
}
Thanks very much
ob
i found the answer on the facebook actionscript issues list:
http://code.google.com/p/facebook-actionscript-api/issues/detail?id=197
I was also trying to find a solution
but the only one is to publish it with
flash player 10
fixed the problem for me
I was facing same issue.Main reason of this issue is Flash Player version.
Use Flash Player 10+ FaceBookGraphApi SWC file is compatible with Flash Player 10.
This solution is only for who are using swc from GraphAPI_Examples_1_6_1

ActionScript - Global Custom Events?

up until now, the way i've been needing to handle my own custom events is by adding an event listener to the object that was dispatching the custom event. while this method of event handling works just fine, i've come to the point where i would like my custom events to be globally accessible, where the listening object does not need to be the same object that is dispatching the event.
in this example, my main Controller class is instantiating and adding to the display list 2 sprite classes: Square and Triangle. the 4th and final class is a custom event called ColorChangeEvent.
i'm attempting to dispatch a new ColorChangeEvent from the Square class, which uses a timer to dispatch a new random color once every second, while Triangle will listen for the dispatched event and change its fill color to the color that was dispatched by Square.
Controller.as:
package
{
import flash.display.Sprite;
public class Controller extends Sprite
{
public function Controller()
{
var sq:Square = new Square();
sq.x = sq.y = 100;
var tr:Triangle = new Triangle();
tr.x = tr.y = 250;
addChild(sq);
addChild(tr);
}
}
}
Square.as:
package
{
import flash.display.Sprite;
import flash.events.TimerEvent;
import flash.utils.Timer;
public class Square extends Sprite
{
public function Square()
{
graphics.beginFill(0x999999);
graphics.drawRect(0, 0, 100, 100);
graphics.endFill();
var myTimer:Timer = new Timer(1000);
myTimer.addEventListener(TimerEvent.TIMER, dispatchNewColor);
myTimer.start();
}
private function dispatchNewColor(evt:TimerEvent):void
{
var randomColor:Number = Math.random() * 0xFFFFFF;
trace("Square Class Dispatched: " + randomColor);
dispatchEvent(new ColorChangeEvent(ColorChangeEvent.CHANGE, randomColor));
}
}
}
Triangle.as:
package
{
import flash.display.Sprite;
import flash.geom.ColorTransform;
public class Triangle extends Sprite
{
public function Triangle()
{
graphics.beginFill(0x999999);
graphics.moveTo(0, 0);
graphics.lineTo(100, 50);
graphics.lineTo(-50, 150);
graphics.endFill();
addEventListener(ColorChangeEvent.CHANGE, changeColor);
}
private function changeColor(evt:ColorChangeEvent):void
{
var ct:ColorTransform = new ColorTransform;
ct.color = evt.color;
transform.colorTransform = ct;
trace("Triangle Class Received: " + evt.color);
}
}
}
ColorChangeEvent.as:
package
{
import flash.events.Event;
public class ColorChangeEvent extends Event
{
public static const CHANGE:String = "change";
public var color:Number;
public function ColorChangeEvent(type:String, color:Number)
{
super(type);
this.color = color;
}
override public function clone():Event
{
return new ColorChangeEvent(type, color);
}
}
}
needless to say, this isn't working.
of course, i could add the event listener to the Square instance in the Controller class, who's event handler could pass that value to Triangle via a public function to change the color, but this is exactly the kind of limitation i'm trying to avoid.
it's not always easy to access and pass a value to a class from where the custom event is dispatched, which is why i'm looking for an actual global solution to handling custom events.
I have been using this class for some time now. To use it you would do this in square:
data.EventManager.instance.publish("someName", randomColor);
and then in your Triangle:
data.EventManager.instance.subscribe("someName", handleColorChange);
private function handleColorChange(color:Number):void {
// implementation here
}
You can even pass the ColorChangeEvent instead of just the color.
data.EventManager.instance.publish(ColorChangeEvent.CHANGE, new ColorChangeEvent(ColorChangeEvent.CHANGE, randomColor);
And then
data.EventManager.instance.subscribe(ColorChangeEvent.CHANGE, handleColorChange);
private function handleColorChange(colorChangeEvent:ColorChangeEvent):void {
// implement here
}
I removed a lot of code that is specific to my projects, so I am not 100% it is usable exactly as-is. But, you should be able to modify it to get it working correctly. If not, let me know and I can try to work it out with you.
This class handles additional things that I will not go into, though you are free to explore. Be aware, however, that anything that subscribes for event notification has a strong reference by the EventManager. That means that if you want to destroy something for garbage collection, you need to call EventManager.instance.cancel(ColorChangeEvent.CHANGE, handleColorChange) before the Triangle instances can be collected.
package data {
import flash.utils.*;
public class EventManager extends Object {
private var _subscribers:Dictionary;
private var _calls:Dictionary;
private var _feeds:Dictionary;
private var _requests:Dictionary;
private var _notify:Dictionary;
private var _services:Dictionary;
private static var __instance:EventManager;
public function EventManager() {
if (__instance) {
trace("EventManager is a Singleton class which should only be accessed via getInstance()");
}
_feeds = new Dictionary(true);
_subscribers = new Dictionary(true);
_requests = new Dictionary(true);
_services = new Dictionary(true);
_notify = new Dictionary(true);
}
public function getFeedData($name:String) {
if (_feeds[$name]) {
return _feeds[$name];
}
return undefined;
}
public function unpublish($name:String) {
var _post:* = _feeds[$name];
delete _feeds[$name];
return _post;
}
public function cancel($name:String, $subscriberFunc:Function, ...args): void {
var _cnt:Number;
var _subscriberArray:Array;
if (_subscribers[$name]) {
for (_cnt = 0; _cnt < _subscribers[$name].length; _cnt++) {
if (_subscribers[$name][_cnt] == $subscriberFunc) {
_subscribers[$name].splice(_cnt, 1);
}
}
}
if (_requests[$name]) {
_subscriberArray = _requests[$name];
_cnt = _subscriberArray.length;
while (_cnt > 0) {
if (_subscriberArray[_cnt] == $subscriberFunc) {
_subscriberArray.splice(_cnt, 1);
}
_cnt--;
}
}
}
public function subscribe($name:String, $subscriber:Function, ...args): void {
var _funcArray:Array;
var _func:Function;
if (_feeds[$name]) {
$subscriber(_feeds[$name]);
}
if (! _subscribers[$name]) {
_subscribers[$name] = new Array();
}
_subscribers[$name].push($subscriber);
if (_notify[$name]) {
_funcArray = _notify[$name];
for each (_func in _funcArray) {
_func();
}
delete _notify[$name];
}
}
public function request($name:String, $feedFunction:Function): void {
var _requestArray:Array;
var _request:Function;
if (! _feeds[$name]) {
if (! _requests[$name]) {
_requests[$name] = new Array();
}
_requests[$name].push($feedFunction);
} else {
$feedFunction(_feeds[$name]);
}
if (_notify[$name]) {
_requestArray = _notify[$name];
for each (_request in _requestArray) {
_request();
}
delete _notify[$name];
}
}
public function publish($name:String, $data:*, $args:Object = null): void {
var _subscriberArray:Array;
var _func:Function;
var cnt:Number = 0;
_feeds[$name] = $data;
if (_subscribers[$name] != undefined) {
_subscriberArray = _subscribers[$name].slice();
_cnt = 0;
while (_cnt < _subscriberArray.length) {
_func = _subscriberArray[_cnt] as Function;
if ($args) {
_func($data, $args);
}else {
_func($data);
}
_cnt++;
}
}
if (_requests[$name]) {
_subscriberArray = _requests[$name].slice();
delete _requests[$name];
_cnt = 0;
while (_cnt < _subscriberArray.length) {
if (_subscriberArray[_cnt] != null) {
_subscriberArray[_cnt]($data);
}
_cnt++;
}
}
}
public function notify($name:String, $subscriber:Function): void {
if (_requests[$name] || _subscribers[$name]) {
$subscriber();
}else {
if (! _notify[$name]) {
_notify[$name] = new Array();
}
_notify[$name].push($subscriber);
}
}
public static function getInstance(): EventManager {
if (! __instance) {
__instance = new EventManager();
}
return __instance;
}
public static function get instance(): EventManager {
return getInstance();
}
}
}
I got this to work by creating a singleton: EventDispatchSingleton that extends EventDispatcher. It's basically an empty singleton that provides the dispatchEvent and add/removeEventListener methods (these are automatically provided by extending EventDispatcher).
Anywhere I want to dispatch an event I import EventDispatchSingleton and then call EventDispatchSingleton.instance.dispatchEvent(<someEvent>);.
Then, wherever I want to listen to that event, I just import EventDispatchSingleton and call EventDispatchSingleton.instance.addEventListener(eventName, callback);
You should look into event bubbling, specificly I think you will find the Capturing phase of the event propagation useful. Take a read of Event propagation from Adobe LiveDocs. It's in the Flex docs, but it is about AS3 Events.
Also Senocular has a good post on Flash Event Bubbling.

Add child to scene from within a class

I'm new to flash in general and have been writing a program with two classes that extend MovieClip (Stems and Star).
I need to create a new Stems object as a child of the scene when the user stops dragging a Star object, but do not know how to reference the scene from within the Star class's code.
I've tried passing the scene into the constructor of the Star and doing sometihng like:
this.scene.addChild (new Stems ());
But apparently that's not how to do it... Below is the code for Stems and Stars, any advice would be appreciated greatly.
package {
import flash.display.MovieClip;
import flash.events.*;
import flash.utils.Timer;
public class Stems extends MovieClip {
public const centreX=1026/2;
public const centreY=600/2;
public var isFlowing:Boolean;
public var flowerType:Number;
public const outerLimit=210;
public const innerLimit=100;
public function Stems(fType:Number) {
this.isFlowing=false;
this.scaleX=this.scaleY= .0007* distanceFromCentre(this.x, this.y);
this.setXY();
trace(distanceFromCentre(this.x, this.y));
if (fType==2) {
gotoAndStop("Aplant");
}
}
public function distanceFromCentre(X:Number, Y:Number):int {
return (Math.sqrt((X-centreX)*(X-centreX)+(Y-centreY)*(Y-centreY)));
}
public function rotateAwayFromCentre():void {
var theX:int=centreX-this.x;
var theY:int = (centreY - this.y) * -1;
var angle = Math.atan(theY/theX)/(Math.PI/180);
if (theX<0) {
angle+=180;
}
if (theX>=0&&theY<0) {
angle+=360;
}
this.rotation = ((angle*-1) + 90)+180;
}
public function setXY() {
do {
var tempX=Math.random()*centreX*2;
var tempY=Math.random()*centreY*2;
} while (distanceFromCentre (tempX, tempY)>this.outerLimit ||
distanceFromCentre (tempX, tempY)<this.innerLimit);
this.x=tempX;
this.y=tempY;
rotateAwayFromCentre();
}
public function getFlowerType():Number {
return this.flowerType;
}
}
}
package {
import flash.display.MovieClip;
import flash.events.*;
import flash.utils.Timer;
public class Star extends MovieClip {
public const sWide=1026;
public const sTall=600;
public var startingX:Number;
public var startingY:Number;
public var starColor:Number;
public var flicker:Timer;
public var canUpdatePos:Boolean=true;
public const innerLimit=280;
public function Star(color:Number, basefl:Number, factorial:Number) {
this.setXY();
this.starColor=color;
this.flicker = new Timer (basefl + factorial * (Math.ceil(100* Math.random ())));
this.flicker.addEventListener(TimerEvent.TIMER, this.tick);
this.addEventListener(MouseEvent.MOUSE_OVER, this.hover);
this.addEventListener(MouseEvent.MOUSE_UP, this.drop);
this.addEventListener(MouseEvent.MOUSE_DOWN, this.drag);
this.addChild (new Stems (2));
this.flicker.start();
this.updateAnimation(0, false);
}
public function distanceOK(X:Number, Y:Number):Boolean {
if (Math.sqrt((X-(sWide/2))*(X-(sWide/2))+(Y-(sTall/2))*(Y-(sTall/2)))>innerLimit) {
return true;
} else {
return false;
}
}
public function setXY() {
do {
var tempX=this.x=Math.random()*sWide;
var tempY=this.y=Math.random()*sTall;
} while (distanceOK (tempX, tempY)==false);
this.startingX=tempX;
this.startingY=tempY;
}
public function tick(event:TimerEvent) {
if (this.canUpdatePos) {
this.setXY();
}
this.updateAnimation(0, false);
this.updateAnimation(this.starColor, false);
}
public function updateAnimation(color:Number, bright:Boolean) {
var brightStr:String;
if (bright) {
brightStr="bright";
} else {
brightStr="low";
}
switch (color) {
case 0 :
this.gotoAndStop("none");
break;
case 1 :
this.gotoAndStop("N" + brightStr);
break;
case 2 :
this.gotoAndStop("A" + brightStr);
break;
case 3 :
this.gotoAndStop("F" + brightStr);
break;
case 4 :
this.gotoAndStop("E" + brightStr);
break;
case 5 :
this.gotoAndStop("S" + brightStr);
break;
}
}
public function hover(event:MouseEvent):void {
this.updateAnimation(this.starColor, true);
this.canUpdatePos=false;
}
public function drop(event:MouseEvent):void {
this.stopDrag();
this.x=this.startingX;
this.y=this.startingY;
this.updateAnimation(0, false);
this.canUpdatePos=true;
}
public function drag(event:MouseEvent):void {
this.startDrag(false);
this.canUpdatePos=false;
}
}
}
The fastest way would be to use the parent variable which references the DisplayObject parent.
var stem:Stems = new Stems(2);
stem.x = x; //optional: set stem coordinates to that of Star
stem.y = y;
parent.addChild(stem);
If you want to add the Stems object to the stage every time a star-drag action stops you need to put the above code inside your drop function.