How to call a function from a Class AS3 - actionscript-3

I'm studying to be a Game Designer, and right now I'm having some issues with my flash game.
the game has a Counter Class, with a Score Class that extends Counter. and it is added to the stage in my PlayScreenA Class.
The Timer starts with a number and decreases every 24frames. but in my Hero Class I can pick up some coins and that coins are going to increase the Time on my Score.
The question is: How I can say in my Hero Class to execute the addToValue function inside the Counter Class?
Pieces of Code:
Creating my score in the PlayScreenA Class:
private var myTime:Score = new Score();
private function create_time (){
myTime.x = 800;
myTime.y = 50;
addChild(myTime);
}
Counter Class:
package
{
import flash.display.MovieClip;
public class Counter extends MovieClip
{
public var currentValue:Number;
public function Counter()
{
reset();
}
public function addToValue( amountToAdd:Number ):void
{
currentValue = currentValue + amountToAdd;
updateDisplay();
}
public function subToValue( amountToSub:Number ):void
{
currentValue = currentValue - amountToSub;
updateDisplay();
}
public function reset():void
{
currentValue = 20;
updateDisplay();
}
public function updateDisplay():void
{
}
}
}
Score Class:
package
{
import flash.text.TextField;
import flash.events.Event;
public class Score extends Counter
{
protected var _timeCounter:int;
public function Score()
{
super();
addEventListener(Event.ENTER_FRAME, onUpdate);
}
override public function updateDisplay():void
{
super.updateDisplay();
scoreDisplay.text = currentValue.toString();
}
protected function onUpdate(e:Event):void
{
_timeCounter++;
trace(currentValue);
if (_timeCounter == 24)
{
this.subToValue( 1 );
_timeCounter = 0;
}
}
}
}
Piece of my Hero Class where I need to Call the function:
for(var i:int; i<collisionList.length;i++)
{
var $collision:platform_tile = collisionList[i];
if($hasCollided = hitbox.hitTestObject($collision.hitBox) && $collision.alpha<0.8 && $collision.alpha>0.6)
{
$collision.alpha=0;
$collision.visible = false;
//Here is where I want to call my subToValue function!
break;
}

since addToValue and subToValue are instance methods, you should provide a reference (an instance variable) to the counter object in your hero object, then call its addToValue or subToValue methods.
var theCounter:Counter;
you should either initiate this in your hero object, or assign a pre-existing counter object through getter/setters. then you can call:
theCounter.addToValue();

I assume you are trying to access the object of Score class created initially in the PlayerScreenA class...
If that is the case then you either derive a relationship between the two classes to pass this object or you could keep a static class keeping track of the function at a global level...
public class AppRefrences
{
public static var addToValueFunc:Function;
}
In Player A Class,
private var myTime:Score = new Score();
private function create_time (){
myTime.x = 800;
myTime.y = 50;
addChild(myTime);
// This is where you set the function
Apprefrences.addToValueFunc = myTime.addToValue;
}
In Hero Class,
for(var i:int; i<collisionList.length;i++)
{
var $collision:platform_tile = collisionList[i];
if($hasCollided = hitbox.hitTestObject($collision.hitBox) && $collision.alpha<0.8 && $collision.alpha>0.6)
{
$collision.alpha=0;
$collision.visible = false;
// This is where you call the function
if(AppRefrences.addToValueFunc != null)
AppRefrences.addToValueFunc(0);
break;
}
Try using getter & setters to control the update of the static variable. I didn't include it for the sake of clarity.

Related

Accessing object parameters from another object actionscript3

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

AS3 Accessing classes and variables

I am new to AS3 and I try to make a simple flash game.
My problem concerns accessing a specific array outside of its class.
I succeeded accessing some variables and function but I am quite stuck on this one.
There are 3 classes : Game which is the main class tied to the flash file, Level1 which spawn background element and enemies, and finally the Enemy class.
The Game class instantiate the Level1 class which spawn enemies (with Enemy class) and push them to an array.
When the enemy get hit, a method in the Enemy class remove it from the display list and then tries to remove it from the array located in the Level1 Class, wich fails and throw :
1119: Access of possibly undefined property level1 through a reference with static type Class.
Another problem is some time the bullets stop in the middle of screen, I havn't been able to track down this bug as well.
Any way, this is my first code related post and if it's too messy, tell me and I'll try to make it more readable.
Sorry for any inconveniance and thank you for your help
-Yaniv
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.text.*;
import flash.geom.Point;
public class Game extends MovieClip
{
public var player:Player;
public var level1:Level1;
public var bullet:Bullet;
private var bullets_arr:Array;
var fire_on : Boolean;
var fire_counter : int;
public function Game()
{
level1=new Level1(this.stage);
player = new Player ;
addChild(player);
player.y = 600;
bullets_arr = [];
addEventListener(Event.ENTER_FRAME,Main);
stage.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler);
stage.addEventListener(MouseEvent.MOUSE_UP,mouseUpHandler);
}
function mouseDownHandler($e:MouseEvent):void
{
fire_on = true;
}
function mouseUpHandler($e:MouseEvent):void
{
fire_on = false;
fire_counter = 0;
}
function fire():void
{
bullet = new Bullet ;
addChild(bullet);
bullet.x = player.x;
bullet.y = player.y - 32;
bullets_arr.push(bullet);
}
public function Main(e: Event):void
{
player.x = mouseX;
if (bullets_arr)
{
for (var m:int = 0; m < bullets_arr.length; m++)
{
bullets_arr[m].y -= 20;
if(level1.enemies_arr)
{
for (var n:int = 0; n < level1.enemies_arr.length; n++)
{
if (bullets_arr[m])
{
if (level1.enemies_arr[n])
{
if (level1.enemies_arr[n].hitTestObject(bullets_arr[m]))
{
if(bullets_arr[m].parent)
{
bullets_arr[m].parent.removeChild(bullets_arr[m]);
bullets_arr.splice(bullets_arr[m],1);
level1.enemies_arr[n].DoDamage(10);
}
}
}
}
}
}
}
}
if(fire_on)
{
fire_counter++;
if(fire_counter == 01)
{
fire();
}
else if(fire_counter >5)
{
fire_counter =0;
}
}
}
}
}
package {
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
public class Level1 extends MovieClip{
var i:int;
var j:int;
var frame :int;
public var enemy:Enemy;
public var enemies_arr:Array;
public function Level1(target:Stage)
{
frame = 0;
enemies_arr = [];
for (var i:int = 0; i < 3; i++)
{
for (var j:int = 0; j < 3; j++)
{
enemy = new Enemy;
enemy.x = j*100 + 260;
enemy.y = i*40 - 150;
target.addChild(enemy);
enemies_arr.push(enemy);
}
}
}
}
}
package
{
import flash.display.MovieClip;
public class Enemy extends MovieClip
{
var Health : int;
var splash:Splash;
function Enemy()
{
Health =30;
}
public function DoDamage(Damage:int)
{
Health -= Damage;
if (Health <= 0)
{
Die();
}
}
public function Die()
{
if(this.parent)
{
this.parent.removeChild(this);
//HERE IS THE ERROR
Game.level1.enemies_arr.splice(this,1);
}
}
}
}
The syntacitical problem you're running into is that you're trying to get level1 from the class Game, when level1 is an instance variable, not a static variable. As an instance variable, level1 is a completely different variable for each instance of game, so if you simply say Game.level1, the compiler wonders, "Which Game?"
To change this, you could simply change level1 into a static variable, by changing this:
public var level1:Level1;
to this:
public static var level1:Level1;
That way the variable would be the same across all instances, and you shouldn't have any trouble accessing it on this line:
Game.level1.enemies_arr.splice(this,1);
I will say though that there could be issues here with certain design principles (it may be that you should use callbacks or signals or something for modularity), but the quick-and-easy fix is to just add the word static to level1's declaration.
You should call level1 on the Game instance.
In a simple way, you could define the Game as Singleton
public class Game extends MovieClip {
private static var _instance:Game;
public static function getInstance():Game {
if (_instance == null) {
_instance = new Game();
}
return _instance ;
}
}
So the Die function will be like this
public function Die()
{
if(this.parent)
{
this.parent.removeChild(this);
//HERE IS THE ERROR
Game.getInstance().level1.enemies_arr.splice(this,1);
}
}

Trying to essentially push details through classes

I am working on a game that creates three circles" red, green, and blue who have 3,2,1 health respectively. They get removed from the stage after their health reaches 0 and it is decremented by 1 per click. I am using a Main.mxml file then I have a Target.as file, as well as RedTarget.as, GreenTarget.as, and BlueTarget.as. My question is that I would like to set everything up in my Target.as file, then push the details such as color, health, and if they are dead or not through those functions. I am having trouble doing that though because I am not sure what I would need in the Target.as and then what I would need to code in each of the colored target files.
Here is my Target.as file:
package com.multiClicker {
//import the needed classes
import flash.display.Shape;
import flash.events.MouseEvent;
import spark.components.Image;
public class Target extends Image {
public function Target() {
//add event listeners
this.addEventListener(MouseEvent.CLICK, onClick);
}
//sets the hp of the target
public function hp():Number {
return hp;
}
//get function that returns false if alpha is <= 0
public function dead():Boolean {
if(alpha <= 0){
return false;
}
return true;
}
//subtracts one from targets HP when clicked
public function onClick(e:MouseEvent = null):void {
//subtracts one from hp each click
hp --;
if(hp <=0) {
this.addEventListener(onEnterFrame);
}
}
//subtracts .1 from the classes alpha
public function onEnterFrame():void{
this.alpha =- .1;
}
//draws the target
public function drawTarget(color):void {
var circle:Shape = new Shape();
circle.graphics.beginFill(color);
circle.graphics.drawCircle(0,0,30);
}
}
}
and then my RedTarget.as file, which is the same as blue and green, except for that they are labeled as such in the variables:
package com.multiClicker {
import flash.events.MouseEvent;
public class RedTarget extends Target{
private var redHP:Number = 3;
private var redDead:Boolean = false;
private var redColor:String = "red";
public function RedTarget()
{
redHP = hp;
redDead = dead;
redColor = color;
//include the super function
super();
}
//subtracts one from targets HP when clicked
override public function onClick(e:MouseEvent=null):void {
super.onClick(e);
//push all to super
}
}
}
Any help on the issue would be great. I have been trying to figure it out throughout the day but have not figured it out.
Are you just asking how to pass variables in when you create the Target object?
public class Target extends Image {
public function Target(hp:Number, dead:Boolean, color:String) {
this.hp = hp;
this.dead = dead;
this.color = color;
}
}
Then you instantiate each target like this:
var redTarget:Target = new Target(3, false, "red");
var greenTarget:Target = new Target(2, false, "green");
etc...

Initialize Assets after Preload

Whenever I export the .swf file of my Flash game, I am receiving "TypeError: Error #1009: Cannot access a property or method of a null object reference.", along with a Runtime Shared Library Preloading Warning for my preloader. I have my timeline organized so that the first and third frames are both empty along with a stop(); command in the Actions layer. The second frame contains a single MovieClip that contains all of my exported assets, which are going to be initialized in the third frame of the timeline. None of my assets, except for the preloader, are exported in the first frame. What changes should I make to my Document Class for it to initialize the assets in the third frame?
Document Class:
package com.gameEngine.documentClass
{
import flash.events.*;
import flash.display.*;
import flash.geom.Point;
import com.gameEngine.assetHolders.*;
import com.gameEngine.assetHolders.Levels.*;
public class Document extends MovieClip
{
private static var _document:Document;
private var preloader:Preloader;
public var mcMain:Player;
public var restartButton:RestartButton;
public var spawnArea:SpawnArea;
public var level_1:Level_1;
public var level_2:Level_2;
public var level_3:Level_3;
public function Document()
{
addEventListener(Event.ADDED_TO_STAGE, init);
_document = this;
preloader = new Preloader(390, this.loaderInfo);
this.addChild(preloader);
preloader.addEventListener("loadComplete", loadAssets);
preloader.addEventListener("preloaderFinished", showLogo);
mcMain = new Player(this);
restartButton = new RestartButton(this);
spawnArea = new SpawnArea();
level_1 = new Level_1(this);
level_2 = new Level_2(this);
level_3 = new Level_3(this);
this.addChild(restartButton);
this.addChild(spawnArea);
this.preloader.x = 400;
this.preloader.y = 250;
restartButton.x = 822.95;
restartButton.y = 19;
spawnArea.x = 400;
spawnArea.y = 250;
trace ("Document Class Initialized");
// constructor code
}
public static function getInstance():Document
{
return _document;
}
private function loadAssets(event:Event):void
{
this.play();
}
private function showLogo(event:Event):void
{
this.removeChild(preloader);
}
public function init(event:Event)
{
if (stage.contains(spawnArea))
{
addChild(mcMain);
}
mcMain.x = spawnArea.x;
mcMain.y = spawnArea.y;
}
}
}
Preloader Class:
package com.gameEngine.assetHolders
{
import com.gameEngine.documentClass.*;
import flash.display.*;
import flash.events.*;
public class Preloader extends MovieClip
{
private var fullWidth:Number;
public var loaderInfo:LoaderInfo;
public function Preloader(fullWidth:Number = 0, loaderInfo:LoaderInfo = null)
{
this.fullWidth = fullWidth;
this.loaderInfo = loaderInfo;
addEventListener(Event.ENTER_FRAME, checkLoad);
}
private function checkLoad (event:Event):void
{
if (loaderInfo.bytesLoaded == loaderInfo.bytesTotal && loaderInfo.bytesTotal != 0)
{
dispatchEvent(new Event("loadComplete"));
phaseOut();
}
updateLoader(loaderInfo.bytesLoaded / loaderInfo.bytesTotal);
}
private function updateLoader(num:Number):void
{
progressBar.width = num * fullWidth;
}
private function phaseOut():void
{
removeEventListener(Event.ENTER_FRAME, checkLoad);
progressBar.gotoAndPlay(2);
if (progressBar.currentFrame == progressBar.totalFrames)
{
phaseComplete();
}
}
private function phaseComplete() : void
{
dispatchEvent(new Event("preloaderFinished"));
}
}
}
You have a lot of race conditions going on here. Many of these events could occur at relatively random times in relation to one another . . . you have to think asynchronously. That is, there can be no assumption that any object exists. E.g., in Document.init(), you check is if the spawnArea exists, but it is almost guaranteed not to at that point, and you never check for it again.
Without making any specific changes, I can recommend a generic solution. For any object (objB) you want loaded after another object (objA) is loaded, have objB created in the objA's ADDED_TO_STAGE handler. A simple example would be:
var objA:Whatever;
var objB:WhateverElse;
[...]
objA = new Whatever();
objA.addEventListener(Event.ADDED_TO_STAGE, objAAddedHnd);
[...]
public function objAAddedHnd(event:Event)
{
// remove the event, if no longer needed:
objA.removeEventListener(Event.ADDED_TO_STAGE, objAAddedHnd);
objB = new WhateverElse();
objB.addEventListener(Event.ADDED_TO_STAGE, objBAddedHnd);
}
[...]
public function objBAddedHnd(event:Event)
{
// remove the event, if no longer needed:
objB.removeEventListener(Event.ADDED_TO_STAGE, objBAddedHnd);
// and so on . . .
}
At this point, it shows that you would need to plan the timeline of object creation.

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.