This is an example of one I found online and used (I'm new to object pooling). It works for a single object type but won't allow me to create a pool of different objects
package
{
import starling.display.DisplayObject;
public class SpritePool
{
private var pool:Array;
private var counter:int;
public function SpritePool(type:Class, len:int)
{
pool = new Array();
counter = len;
var i:int = len;
while(--i > -1)
pool[i] = new type();
}
public function getSprite():DisplayObject
{
if(counter > 0)
return pool[--counter];
else
throw new Error("You exhausted the pool!");
}
public function returnSprite(s:DisplayObject):void
{
pool[counter++] = s;
}
}
}
Here is an example of object pool without object count limit.
import flash.utils.Dictionary;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
public class ObjectPool {
public function ObjectPool()
{
throw new Error("don't create instance");
}
private static const objectDict:Dictionary = new Dictionary();
public static function getObject(c:Class):Object{
//if you want add a object count limit,try to check the count here
if (objectDict[c] == null) {
objectDict[c] = [];
}
var t:Array = objectDict[c] as Array;
if (t.length > 0) {
return t.shift();
} else {
return new c();
}
}
public static function putObject(obj:Object):void {
var c:Class = Class(getDefinitionByName(getQualifiedClassName(obj)));
if (objectDict[c] == null) {
return;
}
var t:Array = objectDict[c] as Array;
if (t && t.indexOf(obj) == -1) {
t.push(obj);
}
}
}
Related
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
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
So, I got this .as file that is called, let say, class A.
class A inside has other 2 classes, class B and class C, and the only class that is inside a package is class A. And it throws that error.
I downloaded this as an example, and it should work, however Flash Builder 4.6 doesn't like it.
The structure of the as file is like this:
imports
variables
class B
class C
package
public class A
/package
Btw, I'm using Flash Builder not Flash CC.
Update, posting code:
import com.adobe.serialization.json.JSON;
import com.shephertz.appwarp.WarpClient;
import com.shephertz.appwarp.listener.ConnectionRequestListener;
import com.shephertz.appwarp.listener.NotificationListener;
import com.shephertz.appwarp.listener.RoomRequestListener;
import com.shephertz.appwarp.listener.ZoneRequestListener;
import com.shephertz.appwarp.messages.Chat;
import com.shephertz.appwarp.messages.LiveResult;
import com.shephertz.appwarp.messages.LiveRoom;
import com.shephertz.appwarp.messages.LiveUser;
import com.shephertz.appwarp.messages.Lobby;
import com.shephertz.appwarp.messages.MatchedRooms;
import com.shephertz.appwarp.messages.Move;
import com.shephertz.appwarp.messages.Room;
import com.shephertz.appwarp.types.ResultCode;
import flash.utils.ByteArray;
var APIKEY:String = "key";
var SECRETEKEY:String = "secretkey";
var Connected:Boolean = false;
var INITIALIZED:Boolean = false;
var client:WarpClient;
var roomID:String;
var State:int = 0;
var User:String;
class connectionListener implements ConnectionRequestListener
{
private var connectFunc:Function;
public function connectionListener(f:Function)
{
connectFunc = f;
}
public function onConnectDone(res:int):void
{
if(res == ResultCode.success)
{
Connected = true;
}
else
{
Connected = false;
}
connectFunc(res);
}
public function onDisConnectDone(res:int):void
{
Connected = false;
}
}
class roomListener implements RoomRequestListener
{
private var connectFunc:Function;
private var joinFunc:Function;
public function roomListener(f:Function,f1:Function)
{
connectFunc = f;
joinFunc = f1;
}
public function onSubscribeRoomDone(event:Room):void
{
if(State == 2)
joinFunc();
else
connectFunc();
}
public function onUnsubscribeRoomDone(event:Room):void
{
}
public function onJoinRoomDone(event:Room):void
{
if(event.result == ResultCode.resource_not_found)
{
if(State == 1)
{
State = 3;
}
client.createRoom("room","admin",2,null);
}
else if(event.result == ResultCode.success)
{
if(State == 1)
{
State = 2;
}
roomID = event.roomId;
client.subscribeRoom(roomID);
}
}
public function onLeaveRoomDone(event:Room):void
{
client.unsubscribeRoom(roomID);
}
public function onGetLiveRoomInfoDone(event:LiveRoom):void
{
}
public function onSetCustomRoomDataDone(event:LiveRoom):void
{
}
public function onUpdatePropertyDone(event:LiveRoom):void
{
}
public function onLockPropertiesDone(result:int):void
{
}
public function onUnlockPropertiesDone(result:int):void
{
}
public function onUpdatePropertiesDone(event:LiveRoom):void
{
}
}
class zoneListener implements ZoneRequestListener
{
public function onCreateRoomDone(event:Room):void
{
roomID = event.roomId;
client.joinRoom(roomID);
}
public function onDeleteRoomDone(event:Room):void
{
}
public function onGetLiveUserInfoDone(event:LiveUser):void
{
}
public function onGetAllRoomsDone(event:LiveResult):void
{
}
public function onGetOnlineUsersDone(event:LiveResult):void
{
}
public function onSetCustomUserInfoDone(event:LiveUser):void
{
}
public function onGetMatchedRoomsDone(event:MatchedRooms):void
{
}
}
class notifylistener implements NotificationListener
{
private var joinFunc:Function;
private var msgFunc:Function;
private var leaveFunc:Function;
public function notifylistener(f:Function)
{
joinFunc = f;
}
public function msgListener(f:Function,f1:Function):void
{
msgFunc = f;
leaveFunc = f1;
}
public function onRoomCreated(event:Room):void
{
}
public function onRoomDestroyed(event:Room):void
{
}
public function onUserLeftRoom(event:Room, user:String):void
{
if(user != User)
{
leaveFunc();
}
}
public function onUserJoinedRoom(event:Room, user:String):void
{
if(State == 3)
joinFunc();
}
public function onUserLeftLobby(event:Lobby, user:String):void
{
}
public function onUserJoinedLobby(event:Lobby, user:String):void
{
}
public function onChatReceived(event:Chat):void
{
if(event.sender != User)
{
var obj:Object = com.adobe.serialization.json.JSON.decode(event.chat);
msgFunc(obj);
}
}
public function onUpdatePeersReceived(update:ByteArray):void
{
}
public function onUserChangeRoomProperty(room:Room, user:String,properties:Object):void
{
}
public function onPrivateChatReceived(sender:String, chat:String):void
{
}
public function onUserChangeRoomProperties(room:Room, user:String,properties:Object, lockTable:Object):void
{
}
public function onMoveCompleted(move:Move):void
{
}
}
package
{
import com.adobe.serialization.json.JSON;
import com.shephertz.appwarp.WarpClient;
public class AppWarp
{
public static var _roomlistener:roomListener;
public static var _zonelistener:zoneListener;
public static var _notifylistener:notifylistener;
public static var _connectionlistener:connectionListener;
private static function generateRandomString(strlen:Number):String{
var chars:String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var num_chars:Number = chars.length - 1;
var randomChar:String = "";
for (var i:Number = 0; i < strlen; i++){
randomChar += chars.charAt(Math.floor(Math.random() * num_chars));
}
return randomChar;
}
public static function connect(f:Function):void
{
if(INITIALIZED == false)
{
WarpClient.initialize(APIKEY, SECRETEKEY);
client = WarpClient.getInstance();
INITIALIZED = true;
}
if(Connected == false)
{
_connectionlistener = new connectionListener(f);
client.setConnectionRequestListener(_connectionlistener);
User = generateRandomString(16);
client.connect(User);
}
else
f(0);
}
public static function join(f1:Function, f2:Function):void
{
_roomlistener = new roomListener(f1,f2);
_zonelistener = new zoneListener();
_notifylistener = new notifylistener(f2);
client.setRoomRequestListener(_roomlistener);
client.setZoneRequestListener(_zonelistener);
client.setNotificationListener(_notifylistener);
State = 1;
client.joinRoomInRange(1,1,true);
}
public static function leave():void
{
client.leaveRoom(roomID);
}
public static function begin(f:Function, f1:Function, dir:int, x:int, y:int):void
{
_notifylistener.msgListener(f, f1);
send(0,dir,x,y);
}
public static function move(dir:int,x:int,y:int):void
{
send(1,dir,x,y);
}
public static function eat(dir:int,x:int,y:int):void
{
send(2,dir,x,y);
}
public static function send(type:int,dir:int,x:int,y:int):void
{
if(Connected == true)
{
var obj:Object = new Object();
obj.type = type;
obj.dir = dir;
obj.x = x;
obj.y = y;
client.sendChat(com.adobe.serialization.json.JSON.encode(obj));
}
}
}
}
I needed to place the package keyword at the very beginning of the .as file, otherwise an error is thrown.
You can only define one class in a package in a file. You can define other classes outside the package, but I don't think that is a good idea as I have observed that in some versions of compiler you have to place it at the beginning and in some at the end. Sometimes, it won't work in anyway.
A better way is to define different classes for each listener in different files. You can use the same package name.
I would recommend creating a single class to listen to all listeners by implementing all base listener classes.
For e.g.
//listener.as
package
{
public class Listener implements ConnectionRequestListener, RoomRequestListener, NotificationListener
{
}
}
I'm debugging an issue where an ArrayCollection on a model isn't getting updated in the UI (even though I see it in the new data).
I was wondering if passing that model into other components, i.e. the top level component, causes problems.
For example, here's my model in the top level:
[Bindable]
private var meetingInfo:MeetingInfoModel;
Now here I am passing it into a component in the same class:
<meetingViewStack:MeetingViewStack id="mainPanelContainer"
newAttachmentsList="{meetingInfo.newAttachmentList}"
meetingInfo="{meetingInfo}"
currentState="{getPanelState(currentState)}"
inCreateMeeting="false"
includeIn="runSinglePanel, runDoublePanel"
height="100%"
width="100%"
/>
And here's how I have that property declared in that MeetingViewStack component:
[Bindable]
public var meetingInfo:MeetingInfoModel = MeetingInfoModel.getInstance();
Should binding work correctly in the MeetingViewStack? Even though that property was passed into it by another component.
I mean I really don't have a compelling need to pass it in. It's a model and I can declare it right there.
Thanks for any helpful tips!
UPDATE:
I have verified that the setter gets called when I updated the meetingInfo property. However, it does not get called when I update an array collection in the meetingInfo model, i.e.
meetingInfo.docsAndAttachmentsList.sort = nameSort;
meetingInfo.docsAndAttachmentsList.refresh();
How can I get that to work? That's what I'm really looking for.
Here's the MeetingInfoModel class:
package com.fmr.transporter.model
{
import com.fmr.transporter.events.CustomEvent;
import com.fmr.transporter.events.xmppServicesEvents.XMPPContactsLoadedEvent;
import com.fmr.transporter.services.httpservices.UserServices;
import com.fmr.transporter.services.xmppservices.XMPPServices;
import com.fmr.transporter.util.util;
import com.fmr.transporter.vo.ContactVO;
import com.fmr.transporter.vo.MeetingVO;
import com.fmr.transporter.vo.ParticipantVO;
import flash.events.EventDispatcher;
import mx.collections.ArrayCollection;
import mx.events.CollectionEvent;
import org.igniterealtime.xiff.data.im.RosterItemVO;
[Bindable]
public final class MeetingInfoModel extends EventDispatcher
{
//Universal INFO
public var generalInfo:GeneralInfoModel;
public var meetingVO:MeetingVO = new MeetingVO();
public var meetingId:String;
public var bulletinBoardLiveMembers:ArrayCollection = new ArrayCollection();
public var xmppServices:XMPPServices;
public var declinedParticipantsGroup:ArrayCollection = new ArrayCollection();
public var notJoinedParticipantsGroup:ArrayCollection = new ArrayCollection();
public var conferenceRoomParticipantsGroup:ArrayCollection = new ArrayCollection();
public var otherLocationParticipantsGroup:ArrayCollection = new ArrayCollection();
public var documentList:ArrayCollection = new ArrayCollection();
public var newAttachmentList:ArrayCollection = new ArrayCollection();
public var docsAndAttachmentsList:ArrayCollection = new ArrayCollection();
public var bulletinBoardMsgList:ArrayCollection = new ArrayCollection();
private var _participantList:ArrayCollection = new ArrayCollection();
public var dismissedMeetingIDs:Array = [];
public var visibleToastWindows:Array = [];
public function MeetingInfoModel()
{
generalInfo = GeneralInfoModel.getInstance();
xmppServices = XMPPServices.getInstance();
_participantList.addEventListener(CollectionEvent.COLLECTION_CHANGE, allParticipantsChangeHandler);
bulletinBoardLiveMembers.addEventListener(CollectionEvent.COLLECTION_CHANGE, bulletinBoardLiveMembersChangeHandler);
}
private static var model:MeetingInfoModel = null;
public static function getInstance():MeetingInfoModel
{
if (model == null)
{
model = new MeetingInfoModel();
}
return model;
}
public function displayToastForThisMeeting(meetingID:Number):Boolean
{
//trace("model::meetingID = " + meetingID);
var doDisplayToast:Boolean = false;
var containsMeetingID:Boolean = false;
//the first one
if(dismissedMeetingIDs.length == 0)
{
//trace("dismissedMeetingIDs.length = 0");
doDisplayToast = true;
dismissedMeetingIDs.push(meetingID);
}
else
{
for(var i:int=0; i < dismissedMeetingIDs.length; i++)
{
//trace("dismissedMeetingIDs[" + i + "] = " + dismissedMeetingIDs[i]);
if(meetingID == dismissedMeetingIDs[i])
{ //this one has already been dismissed
doDisplayToast = false;
containsMeetingID = true;
break;
}
else
{
doDisplayToast = true;
containsMeetingID = false;
}
}
if(containsMeetingID == false)
{
dismissedMeetingIDs.push(meetingID);
}
}
return doDisplayToast;
}
public function setAllParticipants(value:ArrayCollection):void
{
_participantList = value;
dispatchEvent(new CustomEvent(CustomEvent.HAVE_PARTICIPANT_LIST));
calculateGroups();
}
public function getParticipant(loginName:String):ParticipantVO
{
for each (var item:ParticipantVO in _participantList)
{
if (item.loginName == loginName)
{
return item;
}
}
return null;
}
private function allParticipantsChangeHandler(event:CollectionEvent):void
{
calculateGroups();
}
private function bulletinBoardLiveMembersChangeHandler(event:CollectionEvent):void
{
calculateGroups();
}
private function isInRoster( loginName:String ):Boolean {
for each (var newContactVO:ContactVO in model.generalInfo.allGroup)
{
if ( newContactVO.profileVO.email == loginName ) {
return true;
}
}
return false;
}
public function calculateGroups():void
{
var allGroup:ArrayCollection = generalInfo.allGroup;
var participantsRosterGroup:ArrayCollection = new ArrayCollection();
var declinedParticipantsGroup:ArrayCollection = new ArrayCollection();
var notJoinedParticipantsGroup:ArrayCollection = new ArrayCollection();
var conferenceRoomParticipantsGroup:ArrayCollection = new ArrayCollection();
var otherLocationParticipantsGroup:ArrayCollection = new ArrayCollection();
var notDeclinedParticipantsGroup:ArrayCollection = new ArrayCollection();
for each (var item:Object in _participantList)
{
//because participant list contains both people and rooms, we must test to see if this is a participant
if(item is ParticipantVO)
{
var xmppLoginName:String = util.formatEmailToUserName(item.loginName);
for each (var newContactVO:ContactVO in allGroup)
{
if ( item.loginName != model.generalInfo.ownerUser.loginName ) {
var rosterVO:RosterItemVO = newContactVO.rosterItemVO;
if (rosterVO.jid.node == xmppLoginName)
{
try {
var contactVO:ContactVO = new ContactVO();
//add the photo to the roster entry for each person in the meeting
if ( newContactVO.profileVO ) {
rosterVO.photo = newContactVO.profileVO.photo;
contactVO.profileVO = xmppServices.findProfile(rosterVO.jid);
contactVO.profileVO = newContactVO.profileVO;
}
else {
rosterVO.photo = null;
}
contactVO.rosterItemVO = rosterVO;
}
catch (e:Error) {
trace(e.message);
}
if (item.status == "declined")
{
declinedParticipantsGroup.addItem(contactVO);
}
else
{
notDeclinedParticipantsGroup.addItem(contactVO);
}
break;
}
}
}
}
}
for each (var contact:ContactVO in notDeclinedParticipantsGroup)
{
var joined:Boolean = false;
if ( contact.rosterItemVO ) {
for each (var memberName:String in bulletinBoardLiveMembers)
{
if (contact.rosterItemVO.jid.node == memberName)
{
joined = true;
if (contact.rosterItemVO.jid.resource == "theconfroomimsittingin" )
{
conferenceRoomParticipantsGroup.addItem(contact);
}
else
{
otherLocationParticipantsGroup.addItem(contact);
}
//dispatchEvent "DW has joined the meeting"
break;
}
}
}
if (!joined)
{
notJoinedParticipantsGroup.addItem(contact);
}
}
this.notJoinedParticipantsGroup = notJoinedParticipantsGroup;
this.declinedParticipantsGroup = declinedParticipantsGroup;
this.otherLocationParticipantsGroup = otherLocationParticipantsGroup;
this.conferenceRoomParticipantsGroup = conferenceRoomParticipantsGroup;
}
public function clearMeeting():void
{
meetingId = "";
_participantList.removeAll();
docsAndAttachmentsList.removeAll();
documentList.removeAll();
newAttachmentList.removeAll();
bulletinBoardMsgList.removeAll();
bulletinBoardLiveMembers.removeAll();
}
[Bindable]
public function get participantList():ArrayCollection
{
return _participantList;
}
}
}
Think you have the binding the wrong way around.
At the top level it should be:
[Bindable] private var meetingInfo:MeetingInfoModel = MeetingInfoModel.getInstance();
And inside the MeetingViewStack component:
[Bindable] public var meetingInfo:MeetingInfoModel;
It may also depend on what properties in the MeetingInfoModel class are [Bindable].
Ok so my problem is this.
In my main class I have a Boolean type variable. In the external class I have a String type variable.
Is it possible to access the variable in my main class, by using the string value of the variable in my external class. Note that the string value of the external class property matches the main class variable.
I just tryed doing this:
Main class CardGame.as has a variable var slot1:Boolean.
In the external class there is the variable var slot:String = slot1;
I also have this line of code: CardGame['slot'] = false;
It doesn't seem to be working :( . Any help would be appreciated. Thanks
Part of the main class file:
function drawCard():void
{
var card:Card = new Card();
if(slot1 == false)
{
card.x = 30;
slot1 = true;
card.slot = "slot1";
}
else if(slot2 == false)
{
card.x = 190;
slot2 = true;
card.slot = "slot2";
}
else if(slot3 == false)
{
card.x = 350;
slot3 = true;
card.slot = "slot3";
}
else if(slot4 == false)
{
card.x = 510;
slot4 = true;
card.slot = "slot4";
}
else if(slot5 == false)
{
card.x = 670;
slot5 = true;
card.slot = "slot5";
}
else
{
card.x = 830;
slot6 = true;
card.slot = "slot6";
}
card.y = cardY;
cardContainer.addChild(card);
}
And the external file:
import flash.display.MovieClip;
import flash.events.MouseEvent;
import CardGame;
public class Card extends MovieClip
{
public var slot:String;
public function Card()
{
// constructor code
addEventListener(MouseEvent.CLICK, removeCard)
}
function removeCard(event:MouseEvent):void
{
this.parent.removeChild(this);
CardGame['slot'] = false;
}
}
You'll need a few lines of code in the external class:
// in CardGame.as
// declare slot1 as a public var right after the class declaration to insure the
// correct scope
public class CardGame extends MovieClip {
public static var slot1:Boolean;
....
// in external class
import CardGame // depends on where this is in relation to the external class
function theFunction():void {
// somewhere in your external class
var slot:String = CardGame.slot1.toString();
}
// Example classes that show how it works
// Main Class - instantiates ExtClass
package {
import flash.display.Sprite;
public class MainVar extends Sprite {
public static var slot1:Boolean;
private var extClass:ExtClass;
public function MainVar() {
slot1 = true;
this.extClass = new ExtClass();
}
}
}
// External Class accesses static var, modifies static var
package {
public class ExtClass {
public function ExtClass() {
var slot:String = MainVar.slot1.toString();
var index:String = "1";
var slotVar:String = "slot" + index;
trace(slot);
// get the value using a string
trace("String access: ", MainVar[slotVar])
MainVar.slot1 = false;
slot = MainVar.slot1.toString();
trace("Var access: ", slot);
// get the value using a string
trace("String access: ", MainVar[slotVar]);
}
}
}