Facebook Actionscript and IE - actionscript-3

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

Related

Load swf on loaded swf?

I'm on a project created in Flash Builder 4.7 and Flash Professional CS6, nice.
I need the project load's a SWF inside the "preloaded SWF",
The first SWF, loads a second SWF,
This second SWF would be the "Home" of the project.
At this point, it work's perfectly. But when the "Home" try to load other external SWF, it says :
[IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2124"]
The code of the first SWF:
public class InitialSWF extends MovieClip
{
private var _loader_:Loader;
private var _applicationContent_:DisplayObject;
private var _loaderContent_:MovieClip;
private var _loaderIcon_:MovieClip;
public function InitialSWF()
{
super();
_loader_ = new Loader();
_loader_.contentLoaderInfo.addEventListener(Event.COMPLETE,_onComplete_,false,0,true);
_loader_.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,_onIoError_,false,0,true);
_loader_.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,_onProgress_,false,0,true);
_loader_.load(new URLRequest("Home.swf"));
}
private function _onComplete_(param1:Event) : void
{
_applicationContent_ = _loader_.content;
_applicationContent_.visible = true;
stage.addChild(_applicationContent_);
_applicationContent_.addEventListener("onApplicationComplete",_onApplicationComplete_,false,0,true);
_loader_.contentLoaderInfo.removeEventListener(Event.COMPLETE,_onComplete_);
_loader_.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,_onIoError_);
_loader_.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS,_onProgress_);
_loader_.unload();
_loader_ = null;
}
private function _onApplicationComplete_(tmpEvt:Event) : void
{
_applicationContent_.removeEventListener("onApplicationComplete",_onApplicationComplete_);
_loaderContent_.addEventListener("loaderOut",_onLoaderOut_,false,0,true);
// do something
}
private function _onLoaderOut_(param1:Event) : void
{
_loaderContent_.removeEventListener("loaderOut",_onLoaderOut_);
_applicationContent_.visible = true;
stage.removeChild(this);
}
private function _onIoError_(tmpError:IOErrorEvent) : void
{
trace(tmpError);
}
private function _onProgress_(param1:ProgressEvent) : void
{
var _progress_:Number = Math.round(param1.bytesLoaded / param1.bytesTotal * 100);
//Do animation loading
}
And the HomeSWF:
public class SecondarySWF extends Sprite
{
private var _loader_:Loader;
private var _loaderContent_:MovieClip;
private var _loaderIcon_:MovieClip;
private var _applicationContent_:DisplayObject;
public function SecondarySWF()
{
this.addEventListener(Event.ADDED_TO_STAGE,this._GoLogin_,false,0,true);
}
public function _GoLogin_(tmpEvent:Event)
{
_loader_ = new Loader();
_loader_.contentLoaderInfo.addEventListener(Event.COMPLETE,_onComplete_,false,0,true);
_loader_.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,_onIoError_,false,0,true);
_loader_.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,_onProgress_,false,0,true);
_loader_.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
_loader_.load(new URLRequest("SecondarySWF.swf"));
}
private function httpStatusHandler(event:HTTPStatusEvent):void {
trace(event);
}
private function _onComplete_(param1:Event) : *
{
_applicationContent_ = _loader_.content;
_applicationContent_.visible = true;
stage.addChild(_applicationContent_);
_applicationContent_.addEventListener("onApplicationComplete",_onApplicationComplete_,false,0,true);
_loader_.contentLoaderInfo.removeEventListener(Event.COMPLETE,_onComplete_);
_loader_.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,_onIoError_);
_loader_.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS,_onProgress_);
_loader_.unload();
_loader_ = null;
this.removeEventListener(Event.ADDED_TO_STAGE,this._GoLogin_);
}
private function _onApplicationComplete_(param1:Event) : void
{
_applicationContent_.removeEventListener("onApplicationComplete",_onApplicationComplete_);
_loaderContent_.addEventListener("loaderOut",_onLoaderOut_,false,0,true);
// ..
}
private function _onLoaderOut_(param1:Event) : void
{
_loaderContent_.removeEventListener("loaderOut",_onLoaderOut_);
//_applicationContent_.visible = true;
//stage.removeChild(this);
}
private function _onIoError_(tmpError:IOErrorEvent) : void
{
trace(tmpError);
}
private function _onProgress_(param1:ProgressEvent) : void
{
var _progress_:Number = Math.round(param1.bytesLoaded / param1.bytesTotal * 100);
// ..
}
}
ConsoleChromeSWF <-This is an image of the Google console.log, and catch this:
start InitialSWF
Load HomeSWF
Complete loaded of HomeSWF
Start HomeSWF
The link of the Secondary SWF (censored/hidden from public)
Load SecondarySWF
ERROR
I don't know why the Secondary SWF is 100% loaded but return an error... Regards!

Image remains null no matter what I do

I am working on a Action Script project and no matter what I did I wasn't able to get a texture from a Atlas, in the end I had to do some quick changes that I rather not keep. Does anyone know why I cannot get a texture from the createDiabloCrashArt method with this:
package gameObjects
{
import starling.core.Starling;
import starling.display.Image;
import starling.display.MovieClip;
import starling.display.Sprite;
import starling.events.Event;
import starling.utils.deg2rad;
public class Diablo extends Sprite
{
private var _type:int;
private var _speed:int;
private var _distance:int;
private var _alreadyHit:Boolean;
private var _position:String;
private var _hitArea:Image;
private var diabloImage:Image;
private var diabloAnimation:MovieClip;
private var diabloCrashImage:Image;
public function Diablo(_ptype:int, _pdistance:int)
{
super();
this._type = _ptype;
this._distance = _pdistance;
this._speed = GameConstants.DIABLO_SPEED;
_alreadyHit = false;
this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage(e:Event):void
{
this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
createDiabloArt();
}
private function createDiabloArt():void
{ //Gets some other stuff using the same getAtlas but as MovieAnimation and works.
}
private function createDiabloCrashArt():void
{
// trace("diablo_chingo" + _type + "KO");
if (diabloCrashImage == null)
{
diabloCrashImage = new Image(Assets.getAtlas().getTexture("diablo_chingo" + _type + "KO"));
this.addChild(diabloCrashImage);
}
else
{
diabloCrashImage.texture = Assets.getAtlas().getTexture("diablo_chingo" + _type + "KO");
}
diabloCrashImage.visible = false;
}
private function hidePreviousInstance():void
{
if (diabloAnimation != null && _type <= GameConstants.DIABLO_TYPE_4)
{
diabloAnimation.visible = false;
Starling.juggler.remove(diabloAnimation);
}
if (diabloImage != null) diabloImage.visible = false;
}
public function get type():int { return _type; }
public function set type(value:int):void
{
_type = value;
resetForReuse();
hidePreviousInstance();
createDiabloArt();
}
public function get alreadyHit():Boolean { return _alreadyHit; }
public function set alreadyHit(value:Boolean):void
{
_alreadyHit = value;
if (value)
{
diabloCrashImage.visible = true;
if (_type >= GameConstants.DIABLO_TYPE_1 || _type <= GameConstants.DIABLO_TYPE_4)
{
diabloAnimation.visible = false;
}
else
{
diabloImage.visible = false;
Starling.juggler.remove(diabloAnimation);
}
}
}
public function resetForReuse():void
{
this.alreadyHit = false;
this.rotation = deg2rad(0);
}
}
}
But it works by changing the following things:
private function onAddedToStage(e:Event):void
{
this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
createDiabloArt();
createDiabloCrashArt();
}
private function createDiabloCrashArt():void
{
// trace("diablo_chingo" + _type + "KO");
if (diabloCrashImage == null)
{
diabloCrashImage = new Image(Assets.getTexture("Diablo1"));
this.addChild(diabloCrashImage);
}
else
{
diabloCrashImage.texture = Assets.getTexture("Diablo1");
//Assets.getAtlas().getTexture("diablo_chingo" + _type + "KO");
}
diabloCrashImage.visible = false;
}
I verified time and time again with debugger, trace and the like that the right parameters where reaching the function such as _type, as a matter of fact in the long method that I didn't include getting the texture I need using the above syntax worked wonderfully.
I tried to:
Change Image to MovieClip
Initialize before getting to createCrashArt
Getting other textures like the ones I can already display (didn't work)
Staring at it really hard.
Setting a default string for the texture.
None yielded anything until I changed the code to look like in the second snippet, the thing is that I don't get why it didn't work and I rather not depend on a quick fix that may or may not turn into a setback later.
Seriously any help to understand this would be great. I don't even care that ir is working right now I just can't for the life of me figure what was wrong in the first place.
Thanks in advance.
EDIT:
public static function getAtlas():TextureAtlas
{
if (gameTextureAtlas == null)
{
var texture:Texture = getTexture("AtlasTextureGame");
var xml:XML = XML(new AtlasXmlGame());
gameTextureAtlas=new TextureAtlas(texture, xml);
}
return gameTextureAtlas;
}
/**
* Returns a texture from this class based on a string key.
*
* #param name A key that matches a static constant of Bitmap type.
* #return a starling texture.
*/
public static function getTexture(name:String):Texture
{
if (gameTextures[name] == undefined)
{
var bitmap:Bitmap = new Assets[name]();
gameTextures[name]=Texture.fromBitmap(bitmap);
}
//trace("Tomando textura!");
return gameTextures[name];
}
EDIT: Assets class
package
{
import flash.display.Bitmap;
import flash.utils.Dictionary;
import starling.textures.Texture;
import starling.textures.TextureAtlas;
public class Assets
{
/**
* Atlas de texturas.
*/
[Embed(source="../Witchmedia/graphics/Spritesheet/ScarletWitch.png")]
public static const AtlasTextureGame:Class;
[Embed(source="../Witchmedia/graphics/Spritesheet/ScarletWitch.xml", mimeType="application/octet-stream")]
public static const AtlasXmlGame:Class;
/**
* Assets de Fondo y botones.
*/
[Embed(source="../Witchmedia/graphics/bgLayer3.jpg")]
public static const BgLayer1:Class;
[Embed(source="../Witchmedia/graphics/Diablo1.png")]
public static const Diablo1:Class;
/**
* Cache de Texturas
*/
private static var gameTextures:Dictionary = new Dictionary();
private static var gameTextureAtlas:TextureAtlas;
/**
* Returna una instancia del atlas de texturas.
* #return the TextureAtlas instance (Singleton)
*/
public static function getAtlas():TextureAtlas
{
if (gameTextureAtlas == null)
{
var texture:Texture = getTexture("AtlasTextureGame");
var xml:XML = XML(new AtlasXmlGame());
gameTextureAtlas=new TextureAtlas(texture, xml);
}
return gameTextureAtlas;
}
/**
* Returns a texture from this class based on a string key.
*
* #param name A key that matches a static constant of Bitmap type.
* #return a starling texture.
*/
public static function getTexture(name:String):Texture
{
if (gameTextures[name] == undefined)
{
var bitmap:Bitmap = new Assets[name]();
gameTextures[name]=Texture.fromBitmap(bitmap);
}
//trace("Tomando textura!");
return gameTextures[name];
}
}
Can you check with this method, Give the texture declaration in a separate class, i guess it doesnt take the appropriate texture.
public static function getAtlas(atlasNumb:uint = 1):TextureAtlas
{
if(sTextureAtlas[atlasNumb - 1] == null)
{
var texture:Texture = getTexture("AtlasTexture"+atlasNumb);
var xml:XML = XML(create("AtlasXml"+atlasNumb));
sTextureAtlas[atlasNumb-1] = new TextureAtlas(texture, xml);
}
return sTextureAtlas[atlasNumb - 1];
}
private static function create(name:String):Object
{
var textureClass:Class = AssetEmbeds_2x;
return new textureClass[name];
}
And define the textures .png and xml in a separate file called AssetEmbeds_2x.
while calling the texture define like
Assets.getAtlas(1).getTextures("xxx"). I hope it wll

AS3 Trouble accessing a static class from inside a nested symbol

So basically this is a question about why my calling class (Door) can not identify this static variable class (Game State). it is throwing a #1009 error saying I can not access with GameState.gameState. On my stage I have a Symbol (CampaignLevel_001) that contains additional symbols like the calling symbol (Door) and above that as a separate Symbol (GameState) so essentially I am having trouble getting a nested symbol / class talking to another class.
package game.GameStates
{
import game.Assets.Player;
import game.Assets.Turret;
import game.Assets.Door;
import flash.events.Event;
import flash.display.MovieClip;
import flash.geom.Point;
import game.Levels.CampaignLevel_001;
public class GameState extends MovieClip
{
//VARIABLES
public var enemyArray : Array;
public var Bullets : Array = new Array();
public var Keys : Array = new Array();
public var HeldKeys : Array = new Array ();
public var Door : Array = new Array();
public var Terrain : Array = new Array();
public var Turrets : Array = new Array ();
public var Blood : Array = new Array ();
public var Shields : Array = new Array ();
public var Levels : Array = new Array ();
public var NumKeys : int;
public var DoorLock : Boolean = false;
public var PlayerSpawnPoint : Point;
public var CampaignSpawnPoint : Point;
public static var gameState : GameState;
public var player : Player;
public var turret : Turret;
public var PlayerLives : int = 99;
public function GameState()
{ // constructor code
gameState = this;
addEventListener(Event.ADDED_TO_STAGE, Awake);
} // constructor code
private function Awake (e : Event) : void
{
enemyArray = new Array();
trace(enemyArray.length);
}
public function OpenDoor () : void
{
if (NumKeys <= 0)
{
DoorLock = true;
}
if (NumKeys > 0)
{
DoorLock = false;
}
}
public function NextLevel () : void
{
RemoveListeners();
trace("SHOULD BE GOING TO THE NEXT LEVEL");
while (Levels.length > 0)
{
for each (var level in Levels)
{
level.NextLevel ();
}
}
}
public function RespawnPlayer () : void
{
//Spawn Player at player start point
player = new Player();
player.x = PlayerSpawnPoint.x;
player.y = PlayerSpawnPoint.y;
addChild(player);
trace("PLAYER ARRAY IS THIS LONG " + enemyArray.length);
trace("spawned Player!");
}
public function setSpellIcons (spell : String , opacity : int) : void
{
if (spell == "dodge")
{
if (opacity == 0)
{
dodgeSymbol.alpha = 0;
}
if (opacity == 1)
{
dodgeSymbol.alpha = 1;
}
}
if (spell == "shield")
{
if (opacity == 0)
{
shieldSymbol.alpha = 0;
}
if (opacity == 1)
{
shieldSymbol.alpha = 1;
}
}
} //public function setSpellIcons (spell : String , opacity : int) : void
public function RemoveListeners() : void
{
while (enemyArray.length > 0)
{
for each (var enemy : MovieClip in enemyArray)
{
enemy.RemovePlayer ();
}
}
while (Door.length > 0)
{
for each (var door : MovieClip in Door)
{
door.RemoveDoorFunctions ();
}
}
while (Bullets.length > 0)
{
for each (var bullet : MovieClip in Bullets)
{
bullet.RemoveProjectile();
}
}
while (Keys.length > 0)
{
for each (var key : MovieClip in Keys)
{
key.RemoveKey ();
}
}
while (Terrain.length > 0)
{
for each (var terrain : MovieClip in Terrain)
{
terrain.RemoveTerrainListeners();
}
}
while (Turrets.length > 0)
{
for each (var turret in Turrets)
{
turret.RemoveTurretListeners();
}
}
while (Blood.length > 0)
{
for each (var splatter in Blood)
{
splatter.RemoveBlood();
}
}
while (Shields.length > 0)
{
for each (var shield in Shields)
{
shield.RemoveShield();
}
}
} //public function RemoveListeners() : void
}
}
The Class that holds (door)
package game.Levels
{
import game.GameStates.GameState;
import flash.display.MovieClip;
import flash.events.Event;
public class CampaignLevel_001 extends MovieClip
{
var currentLevel : int = currentFrame;
public function CampaignLevel_001()
{ // constructor code
addEventListener(Event.ADDED_TO_STAGE, Awake);
}
private function Awake (e : Event) : void
{
GameState.gameState.Levels.push(this);
gotoAndStop(currentLevel);
trace ("CURRENT LEVEL IS " + currentLevel);
}
public function NextLevel () : void
{
var nextLevel : int = currentFrame + 1;
gotoAndStop(nextLevel);
trace ("NEXT LEVEL IS " + nextLevel);
}
}
}
and the calling class (door) is
package game.Assets
{
import flash.display.MovieClip;
import flash.events.Event;
import game.GameStates.GameState;
public class Door extends MovieClip
{
public function Door()
{ // constructor code
addEventListener(Event.ADDED_TO_STAGE, Awake);
}
private function Awake (e : Event) : void
{
GameState.gameState.Door.push(this);
GameState.gameState.OpenDoor ();
stage.addEventListener(Event.ENTER_FRAME, update);
open.alpha = 0;
}
private function update (e : Event) : void
{
if (GameState.gameState.DoorLock == true)
{
open.alpha = 1;
}
if (GameState.gameState.DoorLock == false)
{
open.alpha = 0;
}
}
public function RemoveDoorFunctions () : void
{
GameState.gameState.Door.splice(GameState.gameState.Door.indexOf(this),1);
stage.removeEventListener(Event.ENTER_FRAME, update);
parent.removeChild(this);
}
}
}
It looks like you're trying to make a Singleton, but haven't added the instance function.
change this:
public static var gameState:GameState;
to:
private static var _gameState:GameState;
and remove the constructor gamestate = this;
and add a function:
public static function get gameState():GameState {
if{_gameState == null) {
_gameState = new GameState();
}
return _gameState;
}
You can then call it and only get the one instance of GameState by:
GameState.gameState.DoorLock == true;
and any other function in GameState the same way

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);
}

Referencing textfield on stage issue

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.