Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    Flash




EventDispatcher -Correct Use



I am trying to get EventDispatcher to send events to other entities without any luck. Here is my attempt:


Code:
Event dispatching class (Creates Sprites):
dispatchEvent(new Event("Move"));


Class to receive events (Sprite):

addEventListener("Move", Move);

public function Move(event:Event):void{
if(this.x <300)
{
this.x += 1;
}
}

I have looked in the Actionscript 3.0 Reference. The example it gives shows the Sprite creating an instance of the class that dispatches events. However, I want the opposite, the dispatching class creates instances of Sprites.



FlashKit > Flash Help > Actionscript 3.0
Posted on: 03-17-2008, 01:16 PM


View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread

Getting Into EventDispatcher
I use FAME. I try to understand, how EventDispather is working. I've created two simple classes:


Code:
import test.Test2
import mx.utils.Delegate;
import mx.events.EventDispatcher;

class test.Test extends Object {
var test2:Test2;

var addEventListener:Function;
var removeEventListener:Function;
var dispatchEvent:Function

function handleConstruct(eventObj) {
TRACE(Flashout.INFO + "handleConstruct called");
}
function Test() {
Flashout.init();
TRACE(Flashout.INFO + "Application started");

EventDispatcher.initialize(this);

var myClass = new test.Test2(1000);
test2.addEventListener('timeout', Delegate.create(this, handleConstruct));

}

// --- Main Entry Point
static function main() {
var test:Test = new Test();
}
}
-------------------------------------------------------------
import mx.events.EventDispatcher;
import mx.utils.Delegate;
class test.Test2 {
var timeInt:Number;

var addEventListener:Function;
var removeEventListener:Function;
var dispatchEvent:Function;

function handleTimer()
{
TRACE(Flashout.INFO + "handleTimer");
dispatchEvent({type:'timeout', target:this, message:'Hey dude the timer is done', time:getTimer()});
clearInterval(timeInt);
}

function Test2(len)
{
EventDispatcher.initialize(this);
timeInt = setInterval(Delegate.create(this, handleTimer), len);
}
}


so, handleTimer() was called, but handleConstruct() wasn't. Where am I wrong? What should I do to fix my problems?

Please, help me. Thanks in advance.

MVC And EventDispatcher
Hi,

I have built a standard MVC framework using the Observer pattern. I am interested in implementing the EventDispatcher into the framework and am trying to understand how to either replace Observer, or how best to intergrate the EventDispatcher into the existing framework. Any information on how to accomplish this would be helpful, but I would like to see a concrete example if possible.

Thanks in advance.

Mark

EventDispatcher, One-to-many Or Many-to-one?
Hi guys,

What's the best circumstance to use EventDispatcher in? I've been told it's in one-to-many situations (where one subject dispatches events to many listeners), but I've been using it in reverse.

e.g. I have a menu system with 20 menu items. Each item dispatches a "clicked" event that is picked up by one listener, the menu container. So here I have a many-to-one situation. Is this the right way to use EventDispatcher? Or is there another way I should be doing this?

Thanks.

EventDispatcher Help?
Hi all. I'm just starting to get into using/writing classes in Flash 8 so please forgive this simple question!

I'm loading an XML file into an array with a class and I need the main FLA to wait on frame 1 until the XML is completely loaded into the array before advancing to frame 2. I think the way to do this is to use an EventDispatcher, correct?

Can anyone show me how to do this? Never tried using EventDispatchers before but I think they might be the best solution.

Thanks!!

MA

EventDispatcher
I've never had to do this, but I think that this is what I need to do

How do I create a new event using EventDispatcher?

I want the event to be called when my container.x>=-200

Is this possible? some code would be helpful

Thanks

Help With EventDispatcher
I'm writing a class to simplify loading XML files. The class just wraps the basic URLLoader. My class Extends EventDispatcher so I can register events with it.

At this point the class dispatches the COMPLETE event and I want to pass along the target from the URLLoader my class wraps.

I'm using the following, what am I missing? The target for the event ends up being XMLLoader, which is my class, where I need target to the URLLoader wrapped by my class. Which makes sense, but I need it to point to my URLLoader.


PHP Code:



private function on_complete( e:Event ):void {
    trace( e.target.data );
    dispatchEvent( new Event( Event.COMPLETE ) );


Help With The EventDispatcher
Hey guys,

I have yet another question. This time about the event dispatcher. I have two files - player.fla and MP3Player.as (class file)

player.fla (first frame actions - there is nothing else in this fla =P)

Code:
var Player:MP3Player = new MP3Player();
Player.listen.onPlaylist = function(obj:Object){
trace(obj);
}
Player.loadPlaylist("playlist.txt",true);
MP3Player.as

Code:
import mx.events.EventDispatcher;
class MP3Player{
var playlist_file:String = "";
var number_of_songs:Number = 0;
var stream:Boolean = true;
var Songs:Array = new Array();

var createEvent:Function;
var dispatchEvent:Function;
var addEventListener:Function;
var handleEvent:Function;
var removeEventListener:Function;

public var listen:Object = new Object;

function MP3Player(){
EventDispatcher.initialize(MP3Player.prototype);
this.addEventListener("onPlaylist",listen);
}

function loadPlaylist(_playlist:String,_stream:Boolean){

playlist_file = _playlist;
stream = _stream;

// load playlist
var loadPlaylist:LoadVars = new LoadVars();
loadPlaylist.onLoad = function(success){
if(success){

dispatchEvent({type:"onPlaylist", target:listen});

}
}
loadPlaylist.load(playlist_file);
}

}
Basically I am trying to set off an event when the playlist has loaded. It seems right to me, but apparently its not because the player.fla never traces "here". Can anyone please help me with this ?

Thanks
Aditya

EventDispatcher Help Please
i have lets say 20 mc on the stage that inherits a custom class. added to stage via addChild.
the class has its constructor function that ads listeners. one to mousevents and other to custom event. i need that when i click on one of these mcs, everyone of them get the custom event and perform an action defines by a function.
is that posible?
i used to do that in as2 with asbroadcaster
plz help on this situation.

EventDispatcher - Please Help
I have a Preloader class which loads any stuff passed to it - swf, jpg, xml, etc.
Second class called Controller is responsible for calling Preloader class to load any stuff.
The Preloader class, dispatches an event to Controller class whenever the specified entity completes loadding.

sequence of events:

1. Controller class - call Preloader to load swf1
2. Preloader class - loads swf1 and dispatches event to Controller
3. Controller class - play swf1
4. Controller class - when swf1 is played completely call Preloader to load and xml
5. Preloader class - loads xml and dispatches back the event to Controller
6. Controller class - now i'm trying to trace the nodes of xml.

Now my problem is that if i do steps 1, 2 and 3 only the code works fine. But as i do steps 1-6, nothing seems to happen.

The swf1 plays, i get the xml into the preloader class but i am not able to trace the nodes of the xml in the Controller class.

It seems that the Controller does not get an event notification for the second event.

I know i'm doing something wrong, but that i hv no idea

Can anyone please look at the attached code and identify what wrong with this.

Any other example with multiple events one after another will also do.

EventDispatcher
I have a class called SlideShow that extends Sprite. I also have a reference to a calls called bio which also extends a Sprite. In the SlideShow class I have a dispacthEvent that fires in a function. The problem I'm getting is the listener in the Bio class is not listening correctly. I thought this would bubble up as both Sprites are of the same parnet.

SlideShow Class

Code:
package com.slideshow {

import flash.display.Sprite;
import flash.events.Event;
import com.slideshow.Bio;


public class SlideShow extends Sprite{

private var _bio : Bio;

public function SlideShow( ){
init();
onShowNextSlide( 0 );
}

private function init() : void {
_bio = new Bio();
_bio.x = 620;
_bio.y = 12;
addChild(_bio);

}

public function onShowNextSlide( ID : Number ) : void {
dispatchEvent(new Event('onNextSlide'));
onStartSlideChange( ID );

}
Bio Class


Code:
package com.slideshow {

import flash.display.Sprite;
import flash.events.Event;

public class Bio extends Sprite{


public function Bio(){
this.alpha = 0;
this.addEventListener('onNextSlide', onRefresh );

}

private function onRefresh( evt : Event ) : void {
trace("Refresh Bio");
}

}
}
It works if I use the line

Code:
_bio.dispatchEvent(new Event('onNextSlide'));
But the problem with the above is I will have other classes that need to listened for the same dispatched event. Lets say I had 2 bio Sprites that needed to listen to the same event.

Help With The EventDispatcher
Hey guys,

I have yet another question. This time about the event dispatcher. I have two files - player.fla and MP3Player.as (class file)

player.fla (first frame actions - there is nothing else in this fla =P)

Code:
var Player:MP3Player = new MP3Player();
Player.listen.onPlaylist = function(obj:Object){
trace(obj);
}
Player.loadPlaylist("playlist.txt",true);
MP3Player.as

Code:
import mx.events.EventDispatcher;
class MP3Player{
var playlist_file:String = "";
var number_of_songs:Number = 0;
var stream:Boolean = true;
var Songs:Array = new Array();

var createEvent:Function;
var dispatchEvent:Function;
var addEventListener:Function;
var handleEvent:Function;
var removeEventListener:Function;

public var listen:Object = new Object;

function MP3Player(){
EventDispatcher.initialize(MP3Player.prototype);
this.addEventListener("onPlaylist",listen);
}

function loadPlaylist(_playlist:String,_stream:Boolean){

playlist_file = _playlist;
stream = _stream;

// load playlist
var loadPlaylist:LoadVars = new LoadVars();
loadPlaylist.onLoad = function(success){
if(success){

dispatchEvent({type:"onPlaylist", target:listen});

}
}
loadPlaylist.load(playlist_file);
}

}
Basically I am trying to set off an event when the playlist has loaded. It seems right to me, but apparently its not because the player.fla never traces "here". Can anyone please help me with this ?

Thanks
Aditya

[AS3] EventDispatcher
Hi guys,


Does anyone have any examples of how to use the EventDispatcher class when you pass an object to it's constructor? I haven't been able to find any examples.

I understand that the object I pass to the EventDispatcher constructor needs to implement IEventDispatcher, but what do I do inside of the addEventListener etc methods, pass the parameters to an instance of EventDispatcher?


ActionScript Code:
package
{
    import flash.utils.ByteArray;
    import flash.utils.EventDispatcher;
    import flash.utils.IEventDispatcher;
 
    public class Foo extends ByteArray implements IEventDispatcher
    {
        private var _dispatcher:EventDispatcher;
 
        public function Foo():void
        {
            _dispatcher = new EventDispatcher(this);
        }
 
        public function addEventListener( ... ):void
        {
            _dispatcher.addEventListener( ... );
        }
 
        ...
 
    }
 
}

If that needs to be done then why does a reference need to be passed to the EventDispatcher constructor?

I'm extending ByteArray which isn't a subclass of EventDispatcher unfortunately.

Any help appreciated.

About EventDispatcher
this is a my Motion class

ActionScript Code:
import mx.events.EventDispatcher;
 
class wm.motions.Motion {
    public function Motion() {
        EventDispatcher.initialize(this);
    }
    public function start() {
        MovieClip.addEventListener("onMotionStarted", this);
        var eventObj = new Object();
        eventObj.target = this;
        eventObj.type = "onMotionStarted";
        this.dispatchEvent(eventObj);
    }
}



but "this.dispatchEvent(eventObj);" is error

Help!!!!

[AS2] Help Using EventDispatcher
Hi peeps,

Been having some trouble using the EventDispatcher which I will try an doutline here, and hopefully you guys can give me some idea where I'm going wrong or point me to a good tutorial for this.

I am trying to dispatch events from one AS2 class and pick them up from another. Now this would usually be very simple except that I am not using components... (I know Macromedia want us to use these for everything but sometimes there just isn't need!) Here's my layout...

Class A connects with the HTML page and runs a Javascript function, it then polls for when a result is returned back. At this point an event is dispatched so that I know my Javascript has returned something.
Class B creates an instance of Class A and listens for the event.
i.e.
DC = new DataConnector();
DC.addEventListener(blah)...
The problem is that I keep being told that the member (DC) is private and cannot be accessed however in my debugging I have made everything public in an attempt to root out the problem. I have imported mx.events.EventDispatcher in both classes and initialized it, as well as setting up properties for the functions used.

I initially kept all of my code solely within classA and it worked fine except that I didn't seem to be able to return a value back to my other classes, so you can see I am going around in circles. The EventDispatcher model seems fanatastic but either I need to up my learning more or Macromedia need to make it easier to use :P

The docs and AS2 Dictionary seem to be out of date (?) as the code examples use the following format...
object.event = function(){
// some stuff
}
However I always get told that I cannot use this type of syntax in a class definition...

Any help appreciated. Thanks in advance.

[AS3] EventDispatcher
QUESTION: Is it true that "Event.ENTER_FRAME" events only work with DisplayObjects?

I tried to add an Event.ENTER_FRAME on a class that just extends "EventDispatcher".

In my example here, when I call "start()", the "loop()" method never fires.
(I purposely did not want to extend a DisplayObject for my own devious reasons. )



ActionScript Code:
package
{   
    import flash.events.Event;
    import flash.events.EventDispatcher;   
   
    public class CarData extends EventDispatcher
    {
        private var _x:Number=0;
        private var _y:Number=0;
 
       
        public function CarData(x:Number,y:Number)
        {
            _x=x;
            _y=y;
       
           
        }
        public function start():void
        {
            addEventListener(Event.ENTER_FRAME,loop);
        }
       
        private function loop(evt:Event):void
        {
            //-----------
            //Logic Here
            //-----------
            trace("running");
       
        }
           
 
 
    }
}

EventDispatcher Help
Urgh, I hate AS2. I can't figure out why my events aren't dispatching. Can anyone spot what I'm doing wrong? Most of the class code isn't visible since it shouldn't be affecting anything

Class:
Code:

import mx.events.EventDispatcher;

class FIButton extends MovieClip {
   
   // PROPERTIES ____________________________
   
   private var __ref:MovieClip;
   private var __text:String;
   private var __color:Number;
   private var __liquid:Boolean;
   private var __description:String;
   
   public var dispatchEvent:Function;
   public var addEventListener:Function;
   public var removeEventListener:Function;
   
   // CONSTRUCTOR ____________________________
   
   public function FIButton(ref_mc:MovieClip, text_str:String, color_num:Number, liquid_bln:Boolean) {
      
      EventDispatcher.initialize(this);
      
      __ref = ref_mc;
      __text = text_str || "Button";
      __color = color_num || 0x999999;
      __liquid = liquid_bln || false;
      
      onRollOver = onDragOver = handleMouseOver;
      
   }
   
   // EVENTS ____________________________
   
   private function handleMouseOver():Void {
      trace("moused over"); // <-- traces correctly
      dispatchEvent({target:this,type:"message"});
   }

FLA:
Code:

var tester:MovieClip = this.attachMovie("button_mc", "test_mc", 100)
var btn:FIButton = new FIButton(tester, "Hello", 0x003366, true);

//***************************************************

myObj = {};
myObj.messagez = function(p_eventObj) {
   trace("myObj received a message");
}
btn.addEventListener("messagez",myObj);

//***************************************************

AS 2: EventDispatcher Question
I get the following error msg when I run the code below
There is no method with the name 'dispatchEvent'.
dispatchEvent(eventObject);

I'm new to this whole EventDispatcher thing, can anyone help?

Thanks
================================================== =======

import mx.events.EventDispatcher
class GalleryItem{
var item_filename:String
var item_width:Number;
var item_height:Number;
var item_caption:String;
var item_type:String;
var item_selected:Boolean;
function GalleryItem(filename, width, height, caption, type, selected){
setItemProperty(this,filename, width, height, caption, type, selected);
}
public function setItemProperty(target,filename, width, height, caption, type, selected){
mx.events.EventDispatcher.initialize(this);//initiliallize EventDispatcher
target.item_filename=filename;
target.item_width=width;
target.item_height=height;
target.item_caption = caption;
target.item_type= type;
target.item_selected= selected;
var eventObject:Object = {target:this, type:'onItemPropertySet'};
dispatchEvent(eventObject);// problematic
}
}

Eventdispatcher With Xml Socket
Hi, I have developed this class which is basically a wrapper of the xmlsocket class. I had to develop this for some developers who need not to be worried about the xmlscoket in detail and are supposed to use just the send and receive data through my methods which in turn use the xmlsocket class "send" and "ondata" methods.

PHP Code:



class CIS {
    var mySocket:XMLSocket;
    public function CIS(ipA:String, portA:Number) {
        var ip:String;
        var port:Number;
        mySocket = new XMLSocket();
        ip = ipA;
        port = portA;
        mySocket.connect(ip, port);
        mySocket.onConnect = function(success) {
            if (success) {
                trace("Connected to "+ip);
            } else {
                trace("Cannot connect to "+ip);
            }
        };
    }
        public function sockOnClose():Void {
        mySocket.onClose = function() {
            trace("Connection closed");
        };
    }
    public function sockClose():Void {
        trace("Closing connection..................");
        mySocket.close();
        trace("Closing Closed");
    }
        // Data to Send
    public function sendData(aData:String):Void {
        trace(aData);
        mySocket.send(aData+"
");
    }
    // Data to receive
    public function recData():String {
        var someStr:String;
        mySocket.onData = function(msg) {
            trace(msg+"
");
            someStr = msg+"
";
            _level0.ecData=someStr;
        };
        return someStr;
    }
}




I use this class in a fla like this


PHP Code:



var mySocket:CIS = new CIS("localhost", PORT);
var vRecData;
vRecData =mySocket.recData();
this.onEnterFrame = function() {
    vRecData = mySocket.recData();
};
mySocket.sockOnClose();




my problems is that I am not able to invoke my custom method "recData" when the system invoked event onData takes place.

send, close , connect happen sweetly, but I cant detect the onData method being invoked in my class.

I tried use onEnterFrame where I constantly keep calling the recData function and when the onData is invoked I get appropriate response. But I dont want to use enterframe coz its a waste consuming so much of memory for a task liek this. I want something like this to work


PHP Code:



var mySocket:CIS = new CIS("localhost", PORT);
mySocket.sendData();// Works nice as I send the data with user interaction
vRecData = mySocket.recData();// HELP, I want the variable vRecData to take up the newly arrived value from the onData method.
mySocket.sockOnClose();// works fine.




Hope I am clear in my explanation.

Thx

Eventdispatcher With Different Classes
I'm trying to experiment with the eventdispatcher. I have created a class
that when a button is click it dispatches the eventObject. I know that the
function is called because I had a trace statement in there. Code is below.

code:
//****Broadcaster****
import mx.events.EventDispatcher

class com.testBroadcast extends MovieClip {

private var txtBr:TextField;

function dispatchEvent() {};
function addEventListener() {};
function removeEventListener() {};

public function testBroadcast() {

EventDispatcher.initialize(this);

}


public function testBroad(t:String):Void {
var eventObject:Object = {target:this, type:"drawn"};

dispatchEvent(eventObject);

}

}
//****end****


Then I created a different class for the listener. The listener in this
class simple calls a trace but it never fires. Code below.

code:
//****Listener****
import mx.events.EventDispatcher

class com.testListen extends MovieClip {

private var txtBr:TextField;
private var myListenerObj:Object = new Object;

function dispatchEvent() {};
function addEventListener() {};
function removeEventListener() {};

public function testListen() {
EventDispatcher.initialize(this);


myListenerObj.drawn = function(evtObj:Object) {
trace("hit");
}

addEventListener("drawn", myListenerObj);
}


}
//****end****


My question is can a broadcaster and listener be in two seperate classes?
If they can, where am I going wrong?

TIA
Jeff

EventDispatcher Or AsBroadcast
i'm trying to write this code that listens for an image that has been loaded. In other words i have three arrays:


Cars:Array=new Array("Mercedes.jpg", "BMW.jpg", "Hummer.jpg");

Homes:Array=new Array("Miami.jpg","LosAngeles.jpg","NewYork.jpg");

Casinos:Array=new Array("LasVegas.jpg","AtlanticCity.jpj","MoheganSu n.jpg");

my container mc has the instance name of "imageholder".


now here's what I'm shooting for; everytime an image is fully loaded into "imageholder" from one of these three arrays, i want a particular action to run. for example if any image from the Cars array is 100% loaded into "imageholder", I want some function I will write to run. like

function CarsisLoaded(){
someaction;
}


and so on...if an image from the Homes array is 100% loaded into "imageholder", i want a different function to run...


so I want to use EventDispatcher or AsBroadcast to do this. I need some help with the code if possible.

Lastly, I need the code to work in Flash 6 and above...

thank you in advance

Eventdispatcher And/or Asbroadcast
i'm trying to write this code that listens for an image that has been loaded. In other words i have three arrays:


Cars:Array=new Array("Mercedes.jpg", "BMW.jpg", "Hummer.jpg");

Homes:Array=new Array("Miami.jpg","LosAngeles.jpg","NewYork.jpg");

Casinos:Array=new Array("LasVegas.jpg","AtlanticCity.jpj","MoheganSu n.jpg");

my container mc has the instance name of "imageholder".


now here's what I'm shooting for; everytime an image is fully loaded into "imageholder" from one of these three arrays, i want a particular action to run. for example if any image from the Cars array is 100% loaded into "imageholder", I want some function I will write to run. like

function CarsisLoaded(){
someaction;
}


and so on...if an image from the Homes array is 100% loaded into "imageholder", i want a different function to run...


so I want to use EventDispatcher or AsBroadcast to do this. I need some help with the code if possible.

Lastly, I need the code to work in Flash 6 and above...

thank you in advance

EventDispatcher Not Dispatching Anything
Hi

I have been scratching my head for a couple of days over this one.
What could incapacitate an EventDispatcher so badly?

Original code:
Class 1 instance makes an instance of Class 2 that makes an instance of Class 3 and lastly a Class 4 instance is made.
- when putting this in motion Class1 instance also sets up and eventlistener
on the Class 2 instance.
Class 4 now fires the event with dipatchEvent(Event.RENDER, true, false));

This does not get registered in the Class 2 instance.
All Classes extends Sprite();

First I thought it didn't bubble up so I moved the dispatcher up a level to Class 3 and so forth until I literally
had this* code not registering the event:


// some code..
appStage.addEventListener(Event.RENDER, someFunc, false, 0, true);
dispatchEvent(new Event(Event.RENDER, true, false));
// some more code..

The imports in all Classes are "import flash.events.*;"

I have done this a thousand times all over in my code and now suddenly it is failing.

So my question is really how to debug for such a bug and what could break the event model so badly?

I have tried all the different things I could imagine so now any "Try doing it this way.." is very welcome

Thanks

Ricki

EventDispatcher / AddEventListener
Hello All ---

I am somewhat confused about using the EventDispatcher class. I was under the assumption that I could dispatch an event of any type(using EventDispatcher Class) and then have an event listener subscribe to that event via addEventListener. For example, I have created a custom component which extends mx.core.UIComponent. I am attempting to dispatch an event then have a listener subscribe to this event. The only way I can get it to work is if I include the v2 Button component. I would prefer not to do this due to file size.

Can someone provide some insight into where I may be tripping up. I was under the assumption that the eventDispatcher/addEventLIstener was not bound to the Button Component.

Thanks for any and all replies.

EventDispatcher - Not Dispatching
First time poster, long time reader. I'm trying something i've never done before and for the life of me i can not figure out why it isn't working. I know there are people here that know a lot more than i do so i'm hoping one of you can help me out. I cut out all the irrelevant code. This is a textbook example, literally taken from the Adobe/Macromedia site, and it still won't fire my event off.

First Chunk, inside my class, i cut out all the irrelevant stuff:

Code:
import mx.events.EventDispatcher;
import mx.remoting.debug.NetDebug;

class dataLoader
{

var dispatchEvent:Function;
var addEventListener:Function;
var removeEventListener:Function;

function dataLoader()
{
NetDebug.initialize();
connectionsDataLoader = this
EventDispatcher.initialize(this);
}

function loadedQueue()
{
dispatchEvent({type:'onQueueComplete',target:this});
}

function errorQueue(code:String, faultString:String)
{
dispatchEvent({type:'onLoadError',target:this,code:code,faultString:faultString});
}
Second Part, listener on stage:


Code:
var summary_DataListener:Object = new Object();
summary_DataListener.onQueueComplete = function(evtObj:Object):Void
{
trace("loading complete" + evtObj);
play();
}
summary_DataLoader = new dataLoader();
summary_DataLoader.addListener("onQueueComplete",summary_DataListener);
summary_DataLoader.init();
I hope someone can point me in the right direction.

EventDispatcher Problem
inside MyFirst.as

import mx.events.EventDispatcher;
class Myfirst {
private var dispatchEvent:Function;
public var addEventListener:Function;
public function Myfirst() {
EventDispatcher.initialize(this);
init_fun();
}
private function init_fun() {
dispatchEvent({type:"firstReady", target:this});
}
}


inside Mysecond.as

import mx.events.EventDispatcher;
class Mysecond {
private var dispatchEvent:Function;
public var addEventListener:Function;
public function Mysecond() {
EventDispatcher.initialize(this);
init_fun();
}
private function init_fun() {
dispatchEvent({type:"secondReady", target:this});
}
}

inside testing.fla

var myFirst1:Myfirst = new Myfirst();
function firstReady_fun() {
trace("firstReady");
second_fun();
}
function secondReady_fun() {
trace("secondReady");
}
myFirst1.addEventListener("firstReady", firstReady_fun);
function second_fun() {
var mySecond1:Mysecond = new Mysecond();
mySecond1.addEventListener("secondReady", secondReady_fun);
}


nothing output

Anyone can help me?
thanks in advance

Eventdispatcher And/or Asbroadcast
i'm trying to write this code that listens for an image that has been loaded. In other words i have three arrays:


Cars:Array=new Array("Mercedes.jpg", "BMW.jpg", "Hummer.jpg");

Homes:Array=new Array("Miami.jpg","LosAngeles.jpg","NewYork.jpg");

Casinos:Array=new Array("LasVegas.jpg","AtlanticCity.jpj","MoheganSu n.jpg");

my container mc has the instance name of "imageholder".


now here's what I'm shooting for; everytime an image is fully loaded into "imageholder" from one of these three arrays, i want a particular action to run. for example if any image from the Cars array is 100% loaded into "imageholder", I want some function I will write to run. like

function CarsisLoaded(){
someaction;
}


and so on...if an image from the Homes array is 100% loaded into "imageholder", i want a different function to run...


so I want to use EventDispatcher or AsBroadcast to do this. I need some help with the code if possible.

Lastly, I need the code to work in Flash 6 and above...

thank you in advance

Eventdispatcher And/or Asbroadcast
i'm trying to write this code that listens for an image that has been loaded. In other words i have three arrays:


Cars:Array=new Array("Mercedes.jpg", "BMW.jpg", "Hummer.jpg");

Homes:Array=new Array("Miami.jpg","LosAngeles.jpg","NewYork.jpg");

Casinos:Array=new Array("LasVegas.jpg","AtlanticCity.jpj","MoheganSu n.jpg");

my container mc has the instance name of "imageholder".


now here's what I'm shooting for; everytime an image is fully loaded into "imageholder" from one of these three arrays, i want a particular action to run. for example if any image from the Cars array is 100% loaded into "imageholder", I want some function I will write to run. like

function CarsisLoaded(){
someaction;
}


and so on...if an image from the Homes array is 100% loaded into "imageholder", i want a different function to run...


so I want to use EventDispatcher or AsBroadcast to do this. I need some help with the code if possible.

Lastly, I need the code to work in Flash 6 and above...

thank you in advance

EventDispatcher From External SWF
Hi all,

In my main application class, i'm loading an external swf (with MovieClipLoader) into an empty movieclip. I'm storing the reference to the movieclip as a property of my class.

In my external movieclip , ive set up an eventDispatcher to dispatch various events that I want my application class to listen to.

Back in my application im adding a listener to the movieclip reference that the swf is loaded into, but I cant seem to get it to hear the event :-S

Does anyone know what i'm doing wrong?

thanx everyone

EventDispatcher Model
Does anyone have a good system for dispatching events, I saw that in as2 many people used a custom event dispatching class..There is an inbuilt one in as3. I also understand that one may often be extending something else and not easily
Code:
class extends EventDispatcher
so the IEventDispatcher needs implementing which im not sure how to do..

but im interested to know if I need a custom class like people used to write for as2..

thanks

EventDispatcher / DispatchEvent Help
Hey all,

Firstly, im very new to using EventDispatcher / dispatchEvent and understanding the event flow.

I have a custom class that has a dispatchEvent within that class, the dispatchEvent is fired once when the function has got a return from php, this is then listened from the root of the main timeline.

When my listener and other essential code is placed onto the root of the timeline it fails and throws an error, but when its wrapped in a function and then the function is called straight away in the root of the timeline it works.

This then brings me to my problem, within that function which I wrapped my essential code and listener I have an Object which I use to store the data that is being sent from php (this Object is defined outside of the function on the root of the timeline)

Within the function I then set the data to the Object, giving the Object the data's value, then underneath I would have started to use that data in different parts of my code.

When I want to use the data from underneath the function which includes the listener etc the Object is set to null, whereas when I use the Object inside the function that I wrapped my code in the data is set correctly like wanted.

I'm guessing this is something to do with the event flow, is there anyway in order to set that data to a global type var which can be used else where, including the root of the timeline, e.g. straight after this first function has ran.

Thanks in advanced, hope I've made this clear
alex

EventDispatcher Between Classes
Say I have a class that's creating movieclips. There are multiple instances on stage. When the user drags one of the clips, some lines need to be drawn. I want that to be managed by another class. I need to let the instance of that line drawing class know when it's time for it to do its work.

I'd like to use EventDispatcher to message between the object instances. But I can't get it working. I can get it to send event messages back to the main timeline, but that's not good enough.

Here's from the line drawing class:


ActionScript Code:
import mx.events.EventDispatcher

class LineDrawer extends MovieClip {
   
    function dispatchEvent() {};
    function addEventListener() {};
    function removeEventListener() {};
   
    function LineDrawer() {
       
        mx.events.EventDispatcher.initialize(this);
       
        var listenerObj:Object = new Object();
        listenerObj.moving = function(evtObj) {
            trace("got a message from the satellite object");
        }
       
        this.addEventListener("moving", listenerObj);
    }
   
}

I'm instantiating the line drawing object and the draggable movie clip creating classes on the main timeline. When I instantiate the movieclips, I'm giving the movieclip creating objects a reference to the line drawer, so that those objects know to whom they should message.

The class that draws the movieclips has code in it that handles the dragging events. It works and effectively sends back messages by EventDispatch to listeners on the main timeline.

What do I need to do to get the listener in the line drawing object to receive messages from the movieclip creation/dragging objects?

EventDispatcher In A Class
I'm making my own AS2 class, let's say Table.

When constructing an instance of the Table class I am using some creating and drawing in some movieclips.

I want to have that when any of the clips are clicked the Table instance dispatches an event saying which clip was clicked on.

I've searched the forums and it seems my problem is that when clicking on the MovieClip I'm out of the Table instance scope so it doesn't know what to do with the dispatch event.

In some other similar (but not exactly the same) examples in the forums LuigiL posted a solution to create a temporary variable to hold a reference to the class instance and use that.

I've posted a shortened version of my class. Assume that I've got all the EventDispatcher code and other variable required. And assume I've got the correct code in my FLA file. It is working, but it seems ugly.

I guess my question is that using this ScopFixer solution seems like an inelegant hack and that I am wondering if there is a better way to do this?







Attach Code

class Table{

var scopeFixer:Table;

public function Table(target:MovieClip){
for(var i=0;i<4;i++){
var curClip:MovieClip=createEmptyMovieClip("setting"+i,1000+i);
//
//code to draw in and place the settings
//
curClip.scopeFixer=this;
curClip.onRelease=function(){
scopeFixer.dispatchEvent({target:this, type:'clicked'});
}
}

}

Why Isn't EventDispatcher Working?
Hi,

I'm trying to get EventDispatcher to work, and it simply won't. I was hoping somebody might be able to spot the error, I've been at this for 2 hours, using http://www.adobe.com/devnet/flash/articles/creating_events.html as a model.

I have a MovieClip symbol called "WindyButton" that contains a Button instance called "btnOutline" and a text field on top of it. The WindyButton symbol is associated with a class, which contains the code:

import mx.events.EventDispatcher
class WindyButton extends MovieClip
{
private var btnOutline:Button;

function dispatchEvent() {};
function addEventListener() {};
function removeEventListener() {};

public function WindyButton()
{
btnOutline.useHandCursor = false;
btnOutline.onRelease = this.c;
mx.events.EventDispatcher.initialize(this);
}
public function c()
{
trace ("sending event...");
var eventObject:Object = {target:this, type:'click'};
dispatchEvent(eventObject);
}
}

Then, I've put an instance of the WindyButton symbol onto my stage, with an instance name of myButton. The first frame of the timeline contains:

var listener:Object = new Object;
listener.click = function(evtObj) {
trace ("event received");
}
myButton.addEventListener("click", listener);

From all the tutorials I've read it seems I'm doing things correctly. But then when I click the button, my trace output only says "sending event..." and never says "event received".

Can anybody see what I'm doing wrong???

I'm using Flash 8 and ActionScript 2.0.

Much thanks
Michael





























Edited: 09/09/2007 at 07:06:59 PM by crazygringo

EventDispatcher And MovieClip
Can anybody please help me understand how a MovieClip and EventDispatcher go hand in hand.

e.g.
I have a box mc on stage. when i select this box mc and move I want to call some function.
Yeah I know I can do that using following code.

ActionScript Code:
var boxselected=false;var listener=new Object();listener.onMouseMove=function(){if(boxselected)trace("box moving");}Mouse.addListener(listener);box.onPress=function(){boxselected=true;}box.onRelease=function(){boxselected=false;}[


Suppose in this case I want a target of some movie clip available in onMouseMove function. This is not possible. However it can be done in EventDispatcher class.
So I want to achieve the same thing with EventDispatcher class.

But I'm confused over how to get this done.

Please Help.

EventDispatcher And XML Events
Hi,
These days I'm learning the different usages of EventDispatcher class and understanding it's working.

Any ways here is my another confusion :
Let me write the code first


ActionScript Code:
//this is menu class which builds a menu based on xml fileimport mx.events.EventDispatcher;class menu extends MovieClip{    private var thisTarget:MovieClip;    public var addEventListener:Function;    public function menu ()    {        thisTarget = this;    }    public function init (xmlFile)    {        var menu_xml = new XML ();        EventDispatcher.initialize (this);        //i can have n number of listeners listening to the xml load event        //so that i can take appropriate actions on different components        var xmlListener = new Object ();        xmlListener.xmlLoaded = function (evtObj)        {            //this outputs undefined            trace (evtObj.target);        };        this.addEventListener ("xmlLoaded", xmlListener);        menu_xml.onLoad = function (succ)        {            if (succ)            {                //this outputs undefined.                trace(thisTarget);                thisTarget.dispatchEvent ({type:"xmlLoaded", target:thisTarget});            }        };        menu_xml.load (xmlFile);    }}


Considering the above code if for example I want to broadcast the event of onLoad of xml to different listeners objects with the scope of movieClip in which the xml object is declared, so that later mcs from the library can be attached dynamically.

However this approach does not seem to work.

Hope i have made my doubt clear.
Answers please.

EventDispatcher: Getting Rid Of The Events
Theory question, more than anything.


ActionScript Code:
var page = _root["pageinstance"+num]; //num is a variable, duh.//page_li:Object = new Object(); // page_listener objectpage_li.onPageLoad = function() {    trace("hey, look, the page loaded");    page.display();}page_li.onPageDisplay = function() {    trace("look at that! The page displayed!");}//page.addEventListener("onPageLoad", page_li);page.addEventListener("onPageDisplay", page_li);page.load();


The code is much more complex than this, but thats the skeleton of it. Anyone, my question to you is that I need to use this over and over again, for each time the user presses a button. My problem is that Flash seems to have trouble when I try visiting a page I've already been to, because the events don't properly execute. I've tried page.removeEventListener(); and delete page_li; but both seem to be ineffective.

Basically, what I'm asking is how can I whip the slate completely clean, so that the next time when Flash goes over this code, it executes properly?

Thanks a lot.

Eventdispatcher Tutorial
has anyone tried this tutorial:

http://www.kirupa.com/developer/acti...dispatcher.htm

and got it to work? I get undefined as the count figure in the output panel.

thanks,

<L>

How To Write An Eventdispatcher
How to write as2.0 using class to respond a simple event handler for several mc's ?

Just as simple as :

button1.onPress = function() {
trace("hello!");
}

button1.onRollOver = function() {
this.gotoAndStop(1);
}
...

does anyone have some good examples of using eventDispatcher method in a class?

EventDispatcher Or AsBroadcast
i'm trying to write this code that listens for an image that has been loaded. In other words i have three arrays:


Cars:Array=new Array("Mercedes.jpg", "BMW.jpg", "Hummer.jpg");

Homes:Array=new Array("Miami.jpg","LosAngeles.jpg","NewYork.jpg");

Casinos:Array=new Array("LasVegas.jpg","AtlanticCity.jpj","MoheganSu n.jpg");

my container mc has the instance name of "imageholder".


now here's what I'm shooting for; everytime an image is fully loaded into "imageholder" from one of these three arrays, i want a particular action to run. for example if any image from the Cars array is 100% loaded into "imageholder", I want some function I will write to run. like

function CarsisLoaded(){
someaction;
}


and so on...if an image from the Homes array is 100% loaded into "imageholder", i want a different function to run...


so I want to use EventDispatcher or AsBroadcast to do this. I need some help with the code if possible.

Lastly, I need the code to work in Flash 6 and above...

thank you in advance

EVENTDISPATCHER AND/OR ASBROADCAST
i'm trying to write this code that listens for an image that has been loaded. In other words i have three arrays:


Cars:Array=new Array("Mercedes.jpg", "BMW.jpg", "Hummer.jpg");

Homes:Array=new Array("Miami.jpg","LosAngeles.jpg","NewYork.jpg");

Casinos:Array=new Array("LasVegas.jpg","AtlanticCity.jpj","MoheganSu n.jpg");

my container mc has the instance name of "imageholder".


now here's what I'm shooting for; everytime an image is fully loaded into "imageholder" from one of these three arrays, i want a particular action to run. for example if any image from the Cars array is 100% loaded into "imageholder", I want some function I will write to run. like

function CarsisLoaded(){
someaction;
}


and so on...if an image from the Homes array is 100% loaded into "imageholder", i want a different function to run...


so I want to use EventDispatcher or AsBroadcast to do this. I need some help with the code if possible.

Lastly, I need the code to work in Flash 6 and above...

thank you in advance

Yet Another EventDispatcher Puzzle
I have two .as classes. FaqList, and FaqRow.

Here's a piece of FaqRow that's of the essence:


Code:
import mx.events.EventDispatcher;
import mx.utils.Delegate;

class FaqRow extends MovieClip {

//vis components
private var questionMC:MovieClip;
private var answerMC:MovieClip;

private var dispatchEvent:Function;
public var addEventListener:Function;
public var removeEventListener:Function;

public static var QUESTION_RELEASED:String = "QUESTION_RELEASED";

public function FaqRow() {
mx.events.EventDispatcher.initialize(this);
}

public function onLoad(Void):Void {
questionMC.onRelease = Delegate.create(this, rowReleased);
}

private function rowReleased(Void):Void {
dispatchEvent(QUESTION_RELEASED);
}
}
Should be self-explanatory enough... my FaqList adds instances of FaqRow to the stage, then I try


Code:
//inside some other method
someRow.addEventListener(FaqRow.QUESTION_RELEASED, Delegate.create(this, rowReleased));

private function rowReleased(obj:Object):Void {
trace(obj.target);
}
And wouldn't you know - I don't get the trace from FaqList... no errors or anything like that... just fails in that AS2-signature silent way.

I'm 99% sure it's some silly error that I'm making, I've been trying to find it. Reading about EventListeners... can't figure it out. Maybe someone here with a fresh look on it?

EventDispatcher Problem
Hey All,

Just recently started with AS3 and have hit a wall with the eventDispatcher and creating custom events. I can't see what I am doing wrong:


My class file:


Code:
package resources.methodCalls{
import flash.display.*;
import flash.net.*;
import flash.events.*;
import flash.media.*;

public class requests {

public var requestedArray : Array = [];


// requests class constructor
public function requests() {
}
public function varCompiler(method:String, url:String, missionID:String, assignment:String, versionID:String) {

//establish opening and closing XML tags
var requestXML:XML =
<shuttleAPI>
<versionID>{versionID}</versionID>
<method>{method}</method>
<assignment>{assignment}</assignment>
<missionid>{missionID}</missionid>
</shuttleAPI>;
//appends interior tags to the recently established XML var
//requestXML.version = versionID;
//requestXML.method = method;
//requestXML.assignment = assignment;
//requestXML.missionid = missionID;

trace(requestXML.toXMLString());

methodRequest(method, url, requestXML);

}

private function dataHandler(event:Event):void {
var dataLoaded:URLLoader = URLLoader(event.target);
trace(dataLoaded.data);
var receivedXML:XML = new XML(dataLoaded.data);
trace("receivedXML = "+receivedXML);
trace("requestedArray ="+requestedArray);
for each (var list:XML in receivedXML.foo) {
trace( "items = "+list );
requestedArray.push(list);
trace( "requestedArray = "+requestedArray );
}
dispatchEvent(new Event("dataLoaded"));
}

public function methodRequest(method:String, url:String, requestXML:XML):void {

var dataRequest : URLRequest = new URLRequest (url);
var dataLoader : URLLoader = new URLLoader ();
var requestVars : URLVariables = new URLVariables ();


requestVars.xml = requestXML;
dataRequest.method = URLRequestMethod.POST;
dataRequest.data = requestVars;


dataLoader.addEventListener(Event.COMPLETE, dataHandler);
dataLoader.load(dataRequest);
}
}
}
The AS on the main timeline:


Code:
import resources.methodCalls.*;

var url:String = "http://##########";
var missionID:String = "1";
var assignment:String = "missionControl";
var versionID:String = "0.0.1";

var camRequest : Object = new requests();


camRequest.varCompiler("getCamList", url, missionID, assignment, versionID);

camRequest.addEventListener("dataLoaded", callbackHandler);

function callbackHandler(event: Event) {
trace("camRequest.requestedArray = "+camRequest.requestedArray);
}
Whenever I execute the code I get the following compiler error:

1180: Call to a possibly undefined method dispatchEvent.

Which is referring to the code I have highlighted in red in the class file.

What am I doing incorrectly?

Thank you for you time and energy.

Nate

EventDispatcher Problems
Hi there, I'm having a strange problem dispatching custom events across different classes. Here's some basic code...

MyEvent.as (extends Event)
public function MyEvent(message : String) {
this.message = message;
}

ClassA.as (extends Sprite)
public function ClassA() {
addEventListener(MyEvent.ACTION, listenerFunction);
}

public function listenerFunction(e : MyEvent) : void {
trace("HEARD");
}

ClassB.as (extends Sprite)
public function ClassB() {
dispatchEvent(new MyEvent("MY MESSAGE"));
}


Now if the event is dispatched in the same class as the event listener is defined, it hears it ok. But the example above doesn't work! Any ideas guys?

Thanks a lot,
Dave

EventDispatcher From External SWF
Hi everyone,

Im having some problems getting events from an external flash movie. In my main application class, i'm loading an external swf (with MovieClipLoader) into an empty movieclip. I'm storing the reference to the movieclip as a property of my class.

In my external movieclip , ive set up an eventDispatcher to dispatch various events that I want my application class to listen to.

Back in my application class, im adding a listener to the movieclip reference that the swf is loaded into, but I cant seem to get it to hear the event :-S

Does anyone know what i'm doing wrong?

thanx in advance
tim

EventDispatcher Problem
hello
i haven't very big skills in components creating..
i try to create a custom slider component..
i tested my component in flash scene.. it works normally..
but when i tried to implement the component in a class ...flash cannot hear my events... the problem is that i can trace the object dispatching the event.. and flash can find traces in functions dispatching my events..
to clarify this is the code for the event dispatching:
ActionScript Flash:

ActionScript Code:
myRestrictedSlider = mcSource.attachMovie("sliderHolder", "myRestrictedSlider", depth++);
myRestrictedSlider.slider_mc._width = __width;
myRestrictedSlider._x = __x;
myRestrictedSlider._y = __y;
myRestrictedSlider.slider_mc.setStyle ("lineColor", 0xCCCCCC);
 
_input.addEventListener("change", Delegate.create(this, updateSteps));
myRestrictedSlider.slider_mc.addEventListener("pressed", Delegate.create(this,getSelection));
myRestrictedSlider.slider_mc.addEventListener("changed", Delegate.create(manageSelection));

the code of function that dispatches event is:
ActionScript Flash:

ActionScript Code:
private function __do_properties ()
{
   mc_arrow_1.onPress = function ()
   {
      this._parent.dispatchEvent (
      {
         type : "pressed", target : this._parent, changed : 1
      });
      this.pressed = true;
      this.oldvalue = this.lock_point
      if (this._parent.mc_arrow_2.getDepth () > this.getDepth ()) this.swapDepths (this._parent.mc_arrow_2)
      this.onMouseMove = function ()
      {
         var _mx = this._parent.__get_x (this._parent._xmouse, 1)
         if (_mx [1] != undefined && _mx [1] > Slider._currentXPos)
         {
            /*****************/
            var oldx = this._x;
            this._x = _mx [1] - this._width / 2;
            this.lock_point = _mx [0];
            if (_mx [1] - this._width / 2 != oldx)
            {
               this._parent.dispatchEvent (
               {
                  type : "changing", target : this._parent, changed : 1
               });
            }
         }
         updateAfterEvent ();
      }
   }
   mc_arrow_1.onRelease = function ()
   {
      if (this.oldvalue != this.lock_point)
      {
         this._parent.dispatchEvent (
         {
            type : "changed", target : this._parent, changed : this._name == "arrow_1" ? 1 : 2
         });
      }
      delete this.onMouseMove;
      this.pressed = false;
   }
   mc_arrow_1.onReleaseOutside = mc_arrow_1.onRelease;
}

thank you

Eventdispatcher And/or Asbroadcast
i'm trying to write this code that listens for an image that has been loaded. In other words i have three arrays:


Cars:Array=new Array("Mercedes.jpg", "BMW.jpg", "Hummer.jpg");

Homes:Array=new Array("Miami.jpg","LosAngeles.jpg","NewYork.jpg");

Casinos:Array=new Array("LasVegas.jpg","AtlanticCity.jpj","MoheganSu n.jpg");

my container mc has the instance name of "imageholder".


now here's what I'm shooting for; everytime an image is fully loaded into "imageholder" from one of these three arrays, i want a particular action to run. for example if any image from the Cars array is 100% loaded into "imageholder", I want some function I will write to run. like

function CarsisLoaded(){
someaction;
}


and so on...if an image from the Homes array is 100% loaded into "imageholder", i want a different function to run...


so I want to use EventDispatcher or AsBroadcast to do this. I need some help with the code if possible.

Lastly, I need the code to work in Flash 6 and above...

thank you in advance

Eventdispatcher And/or Asbroadcast
i'm trying to write this code that listens for an image that has been loaded. In other words i have three arrays:


Cars:Array=new Array("Mercedes.jpg", "BMW.jpg", "Hummer.jpg");

Homes:Array=new Array("Miami.jpg","LosAngeles.jpg","NewYork.jpg");

Casinos:Array=new Array("LasVegas.jpg","AtlanticCity.jpj","MoheganSun.jpg");

my container mc has the instance name of "imageholder".


now here's what I'm shooting for; everytime an image is fully loaded into "imageholder" from one of these three arrays, i want a particular action to run. for example if any image from the Cars array is 100% loaded into "imageholder", I want some function I will write to run. like

function CarsisLoaded(){
someaction;
}


and so on...if an image from the Homes array is 100% loaded into "imageholder", i want a different function to run...


so I want to use EventDispatcher or AsBroadcast to do this. I need some help with the code if possible.

Lastly, I need the code to work in Flash 6 and above...

thank you in advance

EventDispatcher Sample Application
http://shocktime.com/eventdispatcher/

MIEventDispatcher Sample App for demonstrating an event dispatcher model (MIEventDispatcher component coming soon)

MIEventDispatcher is a custom component class which simulates the new event model for Flash MX 2004 components. It was developed as a Flash MX 6 (AS-1) component and can extend any
Flash MX component class with a single line of code. (attachMovie in the component init method)
------------------------------------------------------

I haven't posted the code for the Class yet, but hope to soon. I need to clean out all the garbage. Any idea where I can get the PHP script for posting Actionscript code or some other way of posting AS contextually colored/formatted code?

Hopefully, I'll get the code up tonight. Then I need to work on making it a distributable component (with some documentation

Thanks,
MacTitan

p.s. I didn't think it fit Site Design forum, because I hope to have any issues with my AS addressed here.

DispatchQueue, EventDispatcher - Documentation?
Has anyone got any good documentation on using dispatchQueue in EventDispatcher?

I've searched all of the places I can think of, there doesn't seem to be anything.

Thanks!

Copyright © 2005-08 www.BigResource.com, All rights reserved