Custom Events For A Movieclip Are Not Getting Fired
i am trying to write some custom events for a movieclip using EventDispatcher class. but it seems those events are not getting fired. please help me on this issue.
here is actionscript used in both movieclip and main stage. i am also attaching fla file.
Code: stop();
import mx.transitions.Tween; import mx.transitions.easing.*; import mx.events.EventDispatcher;
var BARS_OPEN:Number = 1; var BARS_CLOSED:Number = 2;
var m_currentStatus:Number = BARS_OPEN; var m_animationTime:Number = 0.25; var m_ttbOpenPos:Number = -328; var m_ttbClosedPos:Number = -85.5; var m_btbOpenPos:Number = 192; var m_btbClosedPos:Number = -50.5;
EventDispatcher.initialize(this);
function closeBars() { if (m_currentStatus != BARS_CLOSED) { m_currentStatus = BARS_CLOSED; animateBars(m_ttbOpenPos, m_ttbClosedPos, m_btbOpenPos, m_btbClosedPos); } }
// function to open transition bars, if it is in closed state function openBars() { if (m_currentStatus != BARS_OPEN) { m_currentStatus = BARS_OPEN; animateBars(m_ttbClosedPos, m_ttbOpenPos, m_btbClosedPos, m_btbOpenPos); } }
function animateBars(ttbFrom:Number, ttbTo:Number, btbFrom:Number, btbTo:Number) { // do bars animation var ttbTween:Tween = new Tween(ttb_mc, "_y", Regular.easeOut, ttbFrom, ttbTo, m_animationTime, true); var btbTween:Tween = new Tween(btb_mc, "_y", Regular.easeOut, btbFrom, btbTo, m_animationTime, true); // broadcast the event once the animation is finished ttbTween.onMotionFinished = function() { dispatchAnimationEvent(); } }
function dispatchAnimationEvent() { trace(m_currentStatus); dispatchEvent({type:((m_currentStatus == BARS_OPEN) ? "onBarsOpened" : "onBarsClosed")}); } and Code: close_btn.onRelease = function() { transition_mc.closeBars(); }
open_btn.onRelease = function() { transition_mc.openBars(); }
openClose_btn.onRelease = function() { var listener:Object = new Object(); transition_mc.onBarsClosed = function(evt:Object) { trace("hello"); //transition_mc.onBarsClosed = null; //transition_mc.openBars(); } transition_mc.addEventListener("onBarsClosed", listener); transition_mc.closeBars(); }
ActionScript.org Forums > ActionScript Forums Group > ActionScript 2.0
Posted on: 06-03-2006, 09:09 AM
View Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
Custom MovieClip Events
Is it possible to extend a class to include custom events, such as different click events? If so, could someone point me to a tutorial or provide a simple example of how this might be done.
Thanks.
_t
Custom Events For Custom Classes
So what I'm trying to build is a custom class wich connects to a php socket server using an XML socket.
I don't know how I can broadcast an event so I can write something like the code below. Anyone can help ?
Attach Code
myClass= new myOwnClass();
myClass.onConnect=connectionHandler;
function connectionHandler{
//do something;
}
Custom Events
I'm reading up into Custom Events and trying to code in a more OOP approach, I've run into a problem.
Basically, I have a main class which loads information about several different "scenes" each composed of their own elements.
For example, the splash scene could consist of four images, a couple of textfields and a button.
I have a scene layout class which has the information pertaining only to the current scene and loads each element.
I was wondering the best way to create an event in the main class.. and then, dispatch it in the scene layout class once every element is done loading.
Is passing a reference of the main class to the scene layout class the only way to do this? If so, is there a better approach to the problem?
AS3 Custom Events Are Mean
I need to start really getting into AS3 events, but I'm really confused.. I have read a lot on custom events but I still can't make them work..
I am trying to make an rts-like selection with the mouse. Click, drag and release. When the user releases the mouse my custom event would be fired and every character on stage would listen to that event and be notified that a mouse selection has been done.
Custom Event:
Code:
package Game{
import flash.events.Event;
import flash.geom.Point;
public class MouseSelection extends Event {
public static const SELECTION:String="selection";
public var StartingPoint:Point;
public function MouseSelection(type:String="selection",bubbles:Boolean=false,cancelable:Boolean=false) {
super(type,bubbles,cancelable);
}
public override function clone():Event {
return new MouseSelection(type, bubbles, cancelable);
}
public override function toString():String {
return formatToString("MouseSelection","StartingPoint","type","bubbles","cancelable");
}
}
}
Main Class :
Code:
package Game{
import flash.display.MovieClip;
import flash.events.*;
import flash.geom.Point;
import flash.display.Shape;
import Game.Character;
import Game.MouseSelection;
public class Main extends MovieClip {
private var StartingMousePoint:Point;
private var MouseIsDown:Boolean=false;
private var MouseSelectionRect:Shape=new Shape();
function Main() {
var Exemple:Character=new Character();
Exemple.x=50;
Exemple.y=50;
addChild(Exemple);
addChild(MouseSelectionRect);
stage.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler);
stage.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
stage.addEventListener(MouseEvent.MOUSE_UP,mouseUpHandler);
stage.addEventListener(MouseSelection.SELECTION, mouseSel);
}
public function mouseSel(event:MouseSelection) {
trace(event);
}
public function mouseDownHandler(event:MouseEvent):void {
MouseIsDown=true;
StartingMousePoint=new Point(event.stageX,event.stageY);
}
public function mouseMoveHandler(event:MouseEvent):void {
if (MouseIsDown) {
var Pt:Point=new Point(event.stageX,event.stageY);
MouseSelectionRect.x=StartingMousePoint.x;
MouseSelectionRect.y=StartingMousePoint.y;
if (MouseSelectionRect.alpha == 0.5 || Point.distance(StartingMousePoint,Pt) > 4) {
MouseSelectionRect.alpha=0.5;
MouseSelectionRect.graphics.clear();
MouseSelectionRect.graphics.beginFill(0x4444FF);
MouseSelectionRect.graphics.lineTo(Pt.x - StartingMousePoint.x,0);
MouseSelectionRect.graphics.lineTo(Pt.x - StartingMousePoint.x,Pt.y - StartingMousePoint.y);
MouseSelectionRect.graphics.lineTo(0,Pt.y - StartingMousePoint.y);
MouseSelectionRect.graphics.lineTo(0,0);
MouseSelectionRect.graphics.endFill();
}
}
}
public function mouseUpHandler(event:MouseEvent):void {
MouseIsDown=false;
if (MouseSelectionRect.alpha == 0.5) {
var MouseSelectionEvent=new MouseSelection();
MouseSelectionEvent.StartingPoint=StartingMousePoint;
dispatchEvent(MouseSelectionEvent);
trace("Dispatch!");
}
MouseSelectionRect.alpha=0;
}
}
}
I have no idea what I have done wrong.. but it just doesn't work!
Custom Events
so I have this class called "gameTimer" as follows:
Code:
package{
import flash.utils.getTimer;
import flash.events.Event;
public class gameTimer
{
private var _gameTime:int;
private var _dT:int;
private var gameInitTime:int;
private var pausePoint:int;
public function init() {
_gameTime = 0;
_dT = 0;
gameInitTime = getTimer();
addEventListener(Event.ENTER_FRAME, update);
}
public function pause() {
pausePoint = getTimer();
removeEventListener(Event.ENTER_FRAME, update);
}
public function restart() {
gameInitTime += getTimer() - pausePoint;
addEventListener(Event.ENTER_FRAME, update);
}
public function kill() {
_gameTime = 0;
_dT = 0;
gameInitTime = 0;
removeEventListener(Event.ENTER_FRAME,update);
}
public function get dT():Number {
return _dT / 1000;
}
public function get dTInt():int {
return _dT;
}
public function get gameTime():Number {
return _gameTime / 1000;
}
public function get gameTimeInt():int {
return _gameTime;
}
public function get realTime():Number {
return (gameInitTime + _gameTime) / 1000;
}
public function get realTimeInt():int {
return gameInitTime + _gameTime;
}
internal function update(e:Event):void {
_dT = getTimer() - _gameTime - gameInitTime;
_gameTime += _dT;
}
override public function toString(): String{
return 'gT: ' + _gameTime + '. dT: ' + _dT + '.';
}
}
}
if anyone wants to use... go ahead it ain't nothing special, I really don't care.
What this timer does is when initialized it starts by taking the current time of the entire movie itself and logs that. Then from there on out it keeps track of how much time has passed since first be initialized in seconds (not milliseconds). You also get access to the amount of time passed since the last time it has updated in seconds (not milliseconds). The timer can also be paused and start back up where it left off with minimal deterioration in accuracy.
Anyways I want to be able to create an Event class that handles an event which fires every 'n' seconds.
My problem is I can't find any good tutorials or help online for constructing custom events beyond adding your own stupid little properties to it. I need extended functions... I also have no idea how the gameT would be accessed to assess the information and fire said event.
If anyone can point me in the direction of any good tutorials... I'd be much appreciative! (yes that's my question... I needs a quality tutorial... google has failed me!)
Custom Events In AS3
I am having trouble finding a real world example of custom events in Flash AS3.
Let's say I have a movieclip with a press event, and another movieclip that I want to change the frame of and they are both on the main timeline. I could use .parent to point from one clip to the other but that can cause issues if I want to change the location of one or both of the clips. If I am building this is in an OOP way how would I make this happen? Thanks!
Eric
Custom Events Help
Here is my code, my problem is with the "getNumJobs" function. If I don't put static in front of public then it won't work and if i do, then it gives me this error: "1120: Access of undefined property nJobs." even though I already defined it as a public var. Any help or solutions??
ActionScript Code:
package
{
import flash.events.*;
public class StartJobEvent extends Event
{
public static const STARTJOB:String = "timerComplete";
public var nJobs:Number;
public var jSpeed:Number;
public function StartJobEvent( type:String, numJobs:Number, jobSpeed:Number, bubbles:Boolean, cancelable:Boolean )
{
nJobs = numJobs;
jSpeed = jobSpeed;
super( type, bubbles, cancelable );
}
public static function getNumJobs():Number
{
return nJobs;
}
}
}
P.S. I am trying to access the "nJobs" variable throughout different parts of my program which is why I need the "getNumJobs" function.
Custom Events In AS3
I am having trouble finding a real world example of custom events in Flash AS3.
Let's say I have a movieclip with a press event, and another movieclip that I want to change the frame of and they are both on the main timeline. I could use .parent to point from one clip to the other but that can cause issues if I want to change the location of one or both of the clips. If I am building this is in an OOP way how would I make this happen?
Regarding Custom Events
I got some difficulties using custom event listeners.
What I would like to achieve is pretty simple. With a bunch of movable fruits, when dragging one of them(this becomes the 'active' object) to collide with others(these are the 'inactive objects'), I need Flash to tell me who is colliding whom.
So I setup the Fruit Class, with the ability to dispatch and listen the custom event: "EXECUTE_HITTEST". For me the code looks good, but there's must be something wrong...
The full .fla & .as files can be downloaded here, and you can preview the snapshot here.
Thanks in advance.
It's in the .zip file as well but for your convenience I just put the Fruit Class here:
================================================================
Attach Code
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
public class Fruit extends MovieClip
{
public function Fruit()
{
initListeners();
}
private function initListeners():void
{
this.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHdlr);
this.addEventListener(MouseEvent.MOUSE_UP, mouseUpHdlr);
//setup the default collision detection listener
this.addEventListener("EXCUTE_HITTEST", executeHitTestHdlr);
}
private function mouseDownHdlr(e:MouseEvent)
{
trace("====== " + this.name + " ======= mouse downed.");
//temporarily disable the C.D. listener when the object becomes 'active'
this.removeEventListener("EXCUTE_HITTEST", executeHitTestHdlr);
//dispatch the "EXECUTE_HITTEST" event based on mouse-moving
this.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHdlr);
startDrag();
}
private function mouseUpHdlr(e:MouseEvent)
{
trace("====== " + this.name + " ======= mouse uped.");
//restore the C.D. listener when the object becomes 'inactive'
this.addEventListener("EXCUTE_HITTEST", executeHitTestHdlr);
//stop dispatching the "EXECUTE_HITTEST" event
this.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHdlr);
stopDrag();
}
// the active object will dispatch the "EXECUTE_HITTEST" EVENT
// when it gets moved
private function mouseMoveHdlr(e:MouseEvent)
{
dispatchEvent(new Event("EXCUTE_HITTEST"));
e.updateAfterEvent();
}
//once inactive objects receive the event, they will do the C.D. checking
private function executeHitTestHdlr(e:Event):void
{
// this= inactive obj.
// e.target = active obj.
trace("----in executeHitTestHdlr-----");
trace("e.target= " + e.target + " name: " + e.target.name); //active obj.
trace("this= " + this + " name: " + this.name); //inactive obj.
if (e.target is Fruit)
{
trace(this.hitTestObject(e.target as Fruit));
}
}
} //EOB class
} //EOB pkg
[AS3] Custom Events
I've written up an example of custom event dispatching in Flash that includes the ability to dispatch events with other parameters to pass on to your handlers. For the sake of brevity, I'm just going to link over to the blog post that explains the whole process and has files available for download.
http://evolve.reintroducing.com/2007...custom-events/
Custom Events Help =(
im making a simple space invader game which has 2 classes called bullet and monsters.
I have a function in the main time line that adds an instance of the bullet class each time the mouse is clicked. There is also a function that adds an instance of the monster class every 3 seconds.
in the bullet class.. i have this snippet of code:
if (this.hitTestObject(monster)== true)
{
addEventListener("enemyHit", testDispatcher);
dispatchEvent(new Event("enemyHit"));
}
the testDispatcher just traces a text so i know that the class is dispatching the event properly
in the monster class, i have this snippet of code:
this.addEventListener("enemyHit", removeMonster);
the removeMonster is just parent.removeChild(this);
So what happens is... the dispatchEvent works in the bullet class only... the maintimeline and the instances of the monster class seems to not receive the enemyHit event... How should i do it so that the monster class can listen for the enemyHit event dispatched by the bullet?
Custom Events
You have some examples of how works custom events in as2?
If I have 2 classes that extends movie clip, how can I make them to comunicate with custom event.?!
Thx,
MIN
Custom Events
I have a simple question: I went through lots of tutorials and can't make it work. What I need is if somenone has a simple example of what should I construct a custom event, for instance I want to detect when a file is loaded, dispatch an event and this event be listened by any other class. So I guess I have a class that loads the file which dispatches the event, and any other/s class/es that listens to that event. Has someone any "simple" example? Thanks
Why Are EVENTS Not Available In A Custom Class?
Code:
class clsCell {
// Some codes here which works.
// The event below does not work
this.onRelease = function() {
mutateMe();
}
}
I get this error:
This statement is not permitted in a class definition.
Can anybody let me know the syntax for creating enabling event handlers within a class?
Thanks
Custom Events In Classes
I want my class called Duck to have an event called finish talking, so that in the fla I can have something like this:
Code:
import Duck;
var dd:Duck;
dd.onFinishTalking = function()
{
//Do stuff
}
How would I code this into my fla. I found the event keyword but I couldnt find the helpdocs in Flash Help files
Custom Listener Events
hi all,
does anybody know if it's possible to create custom listeners? for example, say in a game, i have a character class. i want to add an onKillSomething or an onDie listener to control behaviour instead of constantly checking using onEnterFrame or something similar. it would allow functions to operate independantly.
similarly, how then do i plug into those listeners from another character? i.e. - char1 has an onDie event attached. when he dies i want char2 to know about it. what way do i go about that? is it just attach a listener to char1, then when he dies, call a function that tells all the other players that he's dead, or can i make char2 listen to char1 so that char2 knows when char1 dies as soon as he does - i.e. char1 doesn't need to tell char2 that he's dead, char2 already knows.
i hope i've explained this properly..
thanks
Custom Events Problem,help
//in .fla
var testObj:testEvent = new testEvent();
var eventObj1:Object = new Object();
var eventObj2:Object = new Object();
var eventObj3:Object = new Object();
eventObj1.onSend = function(obj){
trace("type:"+obj.type+" from eventObj1");
}
eventObj2.onSend = function(obj){
trace("type:"+obj.type+" from eventObj2");
}
eventObj1.onComplete = function(obj){
trace("type:"+obj.type+" from eventObj1");
}
//trace(testObj.send("onSend",eventObj1))
testObj.addEventListener("onSend",eventObj1);
testObj.addEventListener("onComplete",eventObj1);
testObj.addEventListener("onSend",eventObj2);
//testObj.addListener("onComplete",eventObj2);
testObj.send("onSend",eventObj2);
testObj.send("onComplete",eventObj1);
//testObj.send("onSend",eventObj2);
-------------------------------------
testEvent.as
-------------------------------------
import mx.events.EventDispatcher;
class testEvent extends MovieClip{
function testEvent(){
//在构造函数中初始化
EventDispatcher.initialize(this);
}
function dispatchEvent(){}
function addEventListener(){}
function removeEventListener(){}
function send(myEvent:String,objs:Object){
var object:Object={targetbjs,type:myEvent};
//trace("send obj is "+ object.target);
dispatchEvent(object);
}
/* public function addListener(info:String,objr:Object){
// add listener
trace("resived obj is "+ objr);
trace(this.addEventListener(info,objr));
};*/
}
sorry for my poor english
question is:
listener was excute double,both eventObj1,2 call the func onSend().
but i want testObj.send("onSend",eventObj2); it will only eventObj2 listen the dispatchEvent and call eventObj2.onSend(),not both
[SOLVED] Custom Events
Here's my problem. I got a class named ShootableBitmap (extends Bitmap (note that Bitmap implements IEventDispatcher)) and I want it to be able to send events to the main timeline when something happens to the object. The problem is I cannot get this to work, and I'm wondering if this is even possible (send events 'out' of an object).
PHP Code:
// In the class:
dispatchEvent(new Event("TEST"));
// In the main timeline:
stage.addEventListener("TEST",ttest);
function ttest(bla:Event):void {
trace("TEST");
}
EDIT: Solved it myself, sorry for posting
[CS3] Custom Events Tutorial?
Does anyone know of any good tutorials for creating custom events, that go beyond just adding new properties to existing events? I'm trying to do a collision event, and I'll probably need to add some functions to do that.
Thanks
Getting Custom Events To Work
I'm trying to dispatch an event every time a player draws a card, which looks like this...
PlayerEvent class
Code:
package actionscript {
import flash.events.Event;
import customactionscript.*;
public class PlayerEvent extends Event {
public static const DRAW_CARD : String = "draw card";
private var _player : Player;
public function PlayerEvent( type : String,
player : Player,
bubbles : Boolean = true,
cancelable : Boolean = false ) {
super( type, bubbles, cancelable );
_player = player;
}
public function get player() : Player {
return _player;
}
override public function clone() : Event {
return new PlayerEvent( type, player, bubbles, cancelable );
}
override public function toString() : String {
return formatToString( "PlayerEvent" , "type" , "player" , "bubbles" , "cancelable", "eventPhase" );
}
}
}
Here's my drawCard function in my Player class
Code:
public function drawCard( numCards : int = 1 ) : void {
while ( numCards-- ) {
if ( _library.length >= 1 ) {
_hand.push( _library.pop() );
dispatchEvent( new PlayerEvent( PlayerEvent.DRAW_CARD , this ) );
}
else {
break;
}
}
}
Now, shouldn't I be able to do this in my document class, and have the event fire off?
Code:
package {
import flash.display.MovieClip;
import customactionscript.*;
public class Game extends MovieClip {
public function Game() {
this.addEventListener( PlayerEvent.DRAW_CARD, cardDrawn );
var player1 : Player = new Player();
player1.drawCard();
}
private function cardDrawn( e : PlayerEvent ) {
trace( e );
}
}
}
The function works, but the event isn't dispatching. Or maybe I just can't listen for it this way, for whatever reason. Either way, it's making it a real pain to test my custom events. What's the deal?
Firing Off Custom Events?
I have several MCs, each performing some actions asynchronously (each has its own setInterval triggered functions). I would like to have each MC fire off a custom event e.g. onActionsComplete. Then I can set up a listener in the main code to be notified of those events. Is that even possible?
Thanks
Problems With Custom Events In AS 3
Hey guys,
First off let me warn you by saying I'm very new to AS 3, and somewhat new to AS in general, so that's why this is probably such a basic problem
So I have a class, which creates another class. Lets just call them Class1 and Class 2 for the sake of arguments.
Class1 has this event listener within the code:
temp.addEventListener( "customEvent", callBackFunction);
temp is a movie clip, and it gets Class2 added to it as a child.
Now somewhere down the line, within class 2, I am running the following:
dispatchEvent( new Event( "customEvent" ) );
First of all, does this all look like legitimate, correct syntax?
Also, I will need to utilize setter and getter functions on the Class2 object when this event is dispatched. Here is the code I threw together in Class1 for that, though I know it also has issues
private function callBackFunction( e : Event ) {
var tempObject: Object = e.target;
tempObject.getSomeValue(); <---just some random, simple function in Class2 that returns a value
}
Please let me know what Im doing wrong and/or what I can do to improve on the above syntax. Thank you!
Sending Custom Events
Hi,
I have two kinda problems that are stumping me.
Question 1
I am trying to connect flash to a MYSQL DB. I have it all set up using php and the flash loader class. I have all of my code in a .as file (Sudo Code):
ActionScript Code:
package{
class talkToDB{
public function readFromDB(....):void{
//Stuff... using loader.
loader.addEventListener(Complete, onLoad);
}
public function onLoad(e:Event):void{
trace(e.currentTarget....);
}
}
}
Calling Code:
ActionScript Code:
var talker:talkToDB = new talkToDB();
talker.readFromDB(...);
So this code works well but it only prints out the DB it cannot return it to the calling function. In a perfect world I would like the Calling code to look like:
ActionScript Code:
var talker:talkToDB = new talkToDB();
var stuffFrom dB:Object = talker.readFromDB(...);
I dont think that I can do this b/c the loader takes time to load.
I think the best thing to do is to have talkToDB pass a custom event back to the Calling code when the Calling code gets the event it can then read a variable from talkToDB.
Second Question
The second thing I am very stumped on is how to send custom events.
I think this should work but it gives me a: 1119: Access of possibly undefined property DONEXML through a reference with static type Class.
ActionScript Code:
package{
import flash.events.Event;
import flash.events.EventDispatcher;
public class SendEvent extends EventDispatcher{
public var DONEXML:String = "doneXML";
public function go() {
trace("START - SendEvent.go()");
dispatchEvent(new Event(SendEvent.DONEXML)); //<-- location of error
trace("Done - SendEvent.go()");
}
}
}
Calling Class:
ActionScript Code:
var a:SendEvent = new SendEvent();
a.addEventListener(a.DONEXML,handler);
a.go();
function handler(e:Event){
trace("This event happened: ");
}
Thanks in advance for any help. If there is a better way to return the stuff from the loader that would be very helpful.
Jake
Custom Events Tutorial?
Hello!
I just got the need to pass an extra parameter along with the event to the event handler, and I read that should be possible with a custom event. So never having used this before, I tried reading up some tutorials on it, but most of them raise more questions than they answer:P Could anyone point me to a ground-up tutorial that explains this stuff?
Thanks in advance!
How Efficient Are Custom Events?
Hello, I am new to the forum and AS3, decent experience with as2 and trying to figure this as3 beast.
I have a simple question (at least I want to think it's simple). Should I rely heavily on custom events throughout my applications? Meaning, should I use event based communication between my classes over composition or inheritance? Maybe I am not even making sense but hey we are here to learn, any tips regarding how much event based driven is a good practice withing as3.
Thanks in advance.
Creating Custom Events
Hi all,
I've been trying to create a custom event for like a day now. I am able to create the basic Event class but the part that I keep getting stuck at is passing an addition argument along with the Event. I have attached my source with this post and I hope someone can help me out or point me in the right direction.
Thanks in advance
Custom Events AHHHHHHRGH
I've learned that working with events along with dynamic content is tricky in as3.
all I need is to pass a number to an event so I can access my arrays and I cannot get it to work.
If someone has time to help or explain what I'm doing wrong thanks ahead of time
here is my code:
ActionScript Code:
package Classes.Events { import flash.events.Event; public class CustomEvent extends Event { public static const MY_ROLLOVER:String = "myRollOver"; public var inter:Number; public function CustomEvent(inter:Number):void { super(MY_ROLLOVER); this.inter = inter; } override public function clone():Event { return new CustomEvent(inter); } }}
In the other script
ActionScript Code:
squareArr[counter].addEventListener(CustomEvent,rollover); squareArr[counter].dispatchEvent(MouseEvent.MOUSE_OVER,CustomEvent(counter));private function rollover(events:CustomEvent){ trace("Ahh");}
and i am getting this error.
Code:
TypeError: Error #1034: Type Coercion failed: cannot convert 0 to Classes.Events.CustomEvent.
at Classes::BuildHome/::fillTheBoard()
at Classes::BuildHome$iinit()
Faster Custom Events
Hi kirupians
I think i have found something i want to share with you
I was making my own event objects using IEventDispatcher and, as always, i was thinking 'do i really need that?' and decided to make my own event system, cutting everything i dont need, like that bubble thing
So i made it, its a bit diferent but not much, instead of
this.addEventListener("alarm", listenerFunction)
for example, if the event type is alarm, it goes:
this.addLAlarm(listenerFunction)
so it goes tht for each event you have his own function to add and remove listeners, so that its not needed to make a internal search for the type of the event
Also, for each event it have an array of internal listeners
And also, when is time to dispatch instead of figuring out what the parameters the event needs, creating an event object,put the parameters on it, dispatch it to each listener function that will get the parameters out of the object, it put the parameters directly on the listener functions
So this way you have to know exactly what parameters each listeners functions will need, and what events yourclass will have
And the results... 7x faster
Events In Custom Classes
Ok I finally realize that I don't understand how the EventDispatcher works.
Or, perhaps, not fully understands it anyway.
My problem:
I've created a custom class, lets call it Bounce. Everytime the ball hits the ground it broadcast the event Event.CHANGE as so:
Code:
disp.dispatchEvent(new Event(Event.CHANGE));
Where disp is a EventDispatcher created when the class Bounce first is created.
Everything works great if I have once Bounce class object on the main timeline, if I add another one the CHANGE for the first one stops triggering but the last one added works instead.
Code:
var bouncyBall:Bounce = new Bounce();
var bouncyBall2:Bounce = new Bounce();
bounceyBall.addEventListener(Event.CHANGE, handler); // this works now
bounceBall2.addEventListener(Event.CHANGE, handler); // after this line one bounceBall2 responds to the Event.CHANGE
Any clues what misstake I'm doing?
Custom Events Are Driving Me Mad :'(
I need to start really getting into AS3 events, but I'm really confused.. I have read a lot on custom events but I still can't make them work..
Custom Event:
Code:
package Game{
import flash.events.Event;
import flash.geom.Point;
public class MouseSelection extends Event {
public static const SELECTION:String="selection";
public var StartingPoint:Point;
public function MouseSelection(type:String,bubbles:Boolean=false,cancelable:Boolean=false) {
super(type,bubbles,cancelable);
}
public override function clone():Event {
return new MouseSelection(type, bubbles, cancelable);
}
public override function toString():String {
return formatToString("MouseSelection","StartingPoint","type","bubbles","cancelable");
}
}
}
Main Class :
Code:
package Game{
import flash.display.MovieClip;
import flash.events.*;
import flash.geom.Point;
import flash.display.Shape;
import Game.MouseSelection;
public class Main extends MovieClip {
private var StartingMousePoint:Point;
private var MouseIsDown:Boolean=false;
private var MouseSelectionRect:Shape=new Shape ;
function Main() {
var Exemple:Character=new Character();
Exemple.x=50;
Exemple.y=50;
addChild(Exemple);
addChild(MouseSelectionRect);
stage.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler);
stage.addEventListener(MouseSelection.SELECTION,mouseSel);
}
public function mouseSel(event:MouseSelection) {
trace(event); // DOES NOT WORKS
}
public function mouseDownHandler(event:MouseEvent):void {
MouseIsDown=true; // WORKS
StartingMousePoint=new Point(event.stageX,event.stageY);
var MouseSelectionEvent:MouseSelection=new MouseSelection(MouseSelection.SELECTION);
MouseSelectionEvent.StartingPoint=StartingMousePoint;
dispatchEvent(MouseSelectionEvent);
trace("Dispatch!");
}
}
}
I have no idea what I have done wrong.. but it just doesn't work! Also, eventually this will need to be in another class (display object) than the main class, it's just easier to work all in the main class at first.
Why One Should/would Make Custom Events?
I guess because I haven't really found a reason to yet, though I'm wondering why people are interested in making custom events - specifically how it is applicable / useful. I understand the ability to pass parameters with custom events, but there's usually been, for me (so far), a few other ways to tackle a problem so that I wouldn't need to write a custom event. In what ways are they useful?
Custom Events Dispatching
Hello everybody,
Task: I want to enter a message in input text field and write it in the dynamic using a custom event dispatching.
Solution:
I have 2 textfields on the stage.
One textfield is an input text field the other is a dynamic text field which will server just to display text.
on the flash in the first frame I made this code:
Code:
var messageBoard:MsgBoard = new MsgBoard(mb); // mb is the instance name of the dynamic text field already placed on the stage
var user1:UserInput = new UserInput(u1); // u1 is the input text field placed on the stage
Also I wrote 3 very simple classes.
1. UserInput.as
Code:
package {
import flash.text.TextField;
import flash.ui.Keyboard;
import flash.events.*;
public class UserInput extends EventDispatcher{
private var textInput:TextField;
public function UserInput(ti:TextField){
textInput = ti;
//listening user input in the input text
textInput.addEventListener(KeyboardEvent.KEY_UP, send_event);
}
private function send_event(evnt:KeyboardEvent):void{
//once enter pressed dispatching our custom event
if(evnt.keyCode == Keyboard.ENTER){
var msg:MsgEvent = new MsgEvent(textInput.text);
this.dispatchEvent(msg);
textInput.text = '';
}
}
}
}
2. MsgEvent.as
Code:
package {
import flash.events.Event;
public class MsgEvent extends Event{
public static const NEW:String = "new_message";
public var msg:String;
public function MsgEvent(str:String){
super(NEW);
msg = str;
}
public override function clone():Event
{
return new MsgEvent(msg);
}
}
}
3. MsgBoard.as
Code:
package {
import flash.text.TextField;
import flash.display.Sprite;
public class MsgBoard extends Sprite{
private var displayTextArea:TextField;
public function MsgBoard(mb:TextField){
displayTextArea = mb;
displayTextArea.text = 'listening to the user input';
// as displayTextArea is a reference to the object that is located on the Stage
// it should have an ability to listen to the events as it's a part of event flow
displayTextArea.addEventListener(MsgEvent.NEW, refreshTextArea);
}
private function refreshTextArea(evnt:MsgEvent):void{
displayTextArea.appendText(evnt.msg);
}
}
}
Problem: Somehow it doesn't work. I actually made it work by making a listener the same object that dispatches the event.
But I want to understand why it doesn't works the way I showed above. I browsed a lot of forums and found that all the
people use to listen by the same object that is dispatching. I think it's like talking with yourself isn't it?
Dispatching Custom Events
Hello
I want to dispatch a custom event and also a string value which can be used by the listener function.
I dont know for some reason I have been getting this error.
"1138: Required parameters are not permitted after optional parameters."
Here is the code for CustomEvent Class
Code:
package {
import flash.events.*;
public class CustomEvent extends Event {
public static const GET_NAME:String = "getname";
public var buttonName:String;
// Constructor
public function CustomEvent (type:String,
bubbles:Boolean = false,
cancelable:Boolean = false,
buttonName:String ) {
super(type, bubbles, cancelable);
this.buttonName = buttonName;
}
public override function clone( ):Event {
return new CustomEvent(type, bubbles, cancelable, buttonName);
}
public override function toString( ):String {
return formatToString("CustomEvent", "type", "bubbles",
"cancelable", "eventPhase", "buttonName");
}
}
}
Here is the code of Btn class where this event is dispatched
Code:
package
{
import flash.display.*;
import flash.text.*;
import flash.events.*;
import flash.geom.ColorTransform;
public class Btn extends Sprite
{
private var nam:String;
public function Btn(lbl:String)
{
this.nam = lbl;
buttonMode = true;
mouseEnabled = true;
_label.mouseEnabled = false;
_label.text = lbl;
addEventListener(MouseEvent.CLICK, onClick);
addEventListener(MouseEvent.MOUSE_OVER, onOver);
addEventListener(MouseEvent.MOUSE_OUT, onOut);
}// end constructor
public function onClick(e:MouseEvent):void
{
trace("Clicked");
dispatchEvent(new CustomEvent(CustomEvent.GET_NAME, true,
false, nam));
}// end onClick
public function onOver(e:MouseEvent):void
{
trace("over");
}// end onOver
public function onOut(e:MouseEvent):void
{
trace("OUT");
}// end onOut
}// end of launch class
}// end package
and the code on the timeline is given as under
Code:
var btn:Btn = new Btn("Soundtrack");
btn.addEventListener(CustomEvent.GET_NAME,
getName);
addChild(btn);
function getName(e:CustomEvent):void
{
trace(e.buttonName);
}
Thanks i nadvance
Custom Events. Are There Any Benefits Of Using Them?
Hi,
I just started to learn ActionScript 3.0 from, "Essential ActionScript 3.0 by Colin Mook". Right now I am reading about custom events and event listeners, but I am confused about the usage. I am not sure when and why I should use them.
I am mildly familiar with the events and event listeners from JavaScript. I find them quite useful because they let us watch (listen) the user behaviour which normally we cannot control (e.g. mouse movement, clicking, key pressing, screen re-size etc.). Which are built-in events.
However, I cannot see the point to create a custom event, and event listener. Because we are doing it in an environment which is totally in our control. We know what will happen, and when it will happen. Here is the example from the book:
Actionscript Code:
// The Game class (the event target)
package {
import flash.events.*;
import flash.utils.*; // Required for the Timer class
public class Game extends EventDispatcher {
public static const GAME_OVER:String = "gameOver";
public function Game ( ) {
// Force the game to end after one second
var timer:Timer = new Timer(1000, 1);
timer.addEventListener(TimerEvent.TIMER, timerListener);
timer.start( );
// A nested function that is executed one second after this object
// is created
function timerListener (e:TimerEvent):void {
endGame( );
}
}
private function endGame ( ):void {
// Perform game-ending duties (code not shown)...
// then ask ActionScript to dispatch an event indicating that
// the game is over
dispatchEvent(new Event(Game.GAME_OVER));
}
}
}
// The Console class (registers a listener for the event)
package {
import flash.display.*;
import flash.events.*;
public class Console extends Sprite {
// Constructor
public function Console ( ) {
var game:Game = new Game( );
game.addEventListener(Game.GAME_OVER, gameOverListener);
}
private function gameOverListener (e:Event):void {
trace("The game has ended!");
// Display "back to console" UI (code not shown)
}
}
}
Now I think this can be achieved without creating a custom event. Game ends after 1 second, and we already have a event listener (built-in) for it. After 1 second, I can just call the function endGame(), like:
Actionscript Code:
// The Game class (the event target)
package {
import flash.events.*;
import flash.utils.*; // Required for the Timer class
public class Game extends EventDispatcher {
public function Game ( ) {
// Force the game to end after one second
var timer:Timer = new Timer(1000, 1);
timer.addEventListener(TimerEvent.TIMER, timerListener);
timer.start( );
// A nested function that is executed one second after this object
// is created
function timerListener (e:TimerEvent):void {
endGame( );
}
}
private function endGame ( ):void {
// Perform game-ending duties (code not shown)...
trace("The game has ended!");
}
}
}
// The Console class (registers a listener for the event)
package {
import flash.display.*;
import flash.events.*;
public class Console extends Sprite {
// Constructor
public function Console ( ) {
var game:Game = new Game( );
}
}
}
Can someone please point me the right direction? What are the benefits of using custom event in the code above.
Thanks for any replies
Custom Events In Flash AS3
I am having trouble finding a real world example of custom events in Flash AS3.
Let's say I have a movieclip with a press event, and another movieclip that I want to change the frame of and they are both on the main timeline. I could use .parent to point from one clip to the other but that can cause issues if I want to change the location of one or both of the clips. If I am building this is in an OOP way how would I make this happen?
Custom Events And Listeners
ok. I have a MainMav class which holds instances of my MainNavButton class. When one is selected I want to remove all the button events and add a listener to a custom event I created so when I click another button in the nav it will dispatch my custom event and trigger a function that will restore the button's events. For what ever reason I can't get it to work. I tried using Lee's script from the OOP Scrollbar tutorial example but I can't seem to get it right. I don't know if I'm implementing it right or not. I used his code for another custom listener and it works fine. But this one just won't work.
this is the event code with a test i made to try it out.
Event Code
Code:
package {
import flash.events.*;
public class ActivateMainNavButtonEvent extends Event {
public static const ACTIVATE_BUTTON = "button";
public function ActivateMainNavButtonEvent():void {
trace("from activate button event");
super(ACTIVATE_BUTTON);
}
}
}
code from an as3 fla that I made to test the code
it doesn't work
Code:
mc2.addEventListener(ActivateMainNavButtonEvent.ACTIVATE_BUTTON, setButton);
mc1.addEventListener(MouseEvent.CLICK, mc1_CLICK);
function mc1_CLICK(e:MouseEvent):void {
dispatchEvent(new ActivateMainNavButtonEvent());
}
function setButton (e:Event):void {
trace("button activated");
}
Anyone have any ideas why this wouldn't work?
or maybe a better way of accomplishing what I want to do.
Dispatching And Listening To Custom Events
I need to "dispatch" an event from a child so that the "parent" will "listen" to it.
I created the parent (forCosito.fla) which instantiates the child (Cosito.as), which dispatches the event (CositoEvent.as) once the count of mouseOvers gets to 3. (all of this is in the attached Cosito.zip file, with all other files needed to run the example, just click on forCosito.swf).
The event gets dispatched, as the traces show, however, it does not get listened to. I tried adding the eventlistener to the stage, to "this", to other movieClips that I placed on the parent just to act as listeners.... I CANNOT get it to work
PLEASE, what am I doing wrong???? I hope somebody out there can help me....
Mariana
Calling UpdateAfterEvent() With Custom Events
Hello,
I am calling a custom event when my character lands on the final space of the game board.
Unfortunately before the character lands on this space the custom event is fired and the character never actually lands on the space itself.
Is there a way to refresh the screen so I can see the character land before the event is fired off?
I guess I could go the cheesy route and just create a 2-3 second timer that would fire this custom event with the hopes that the screen would be refreshed within this 2-3 second time frame.
I kinda wished there was an additonal parameter for events that allowed you to place an execution delay on them...wishful thinking I guess.
many thanks for any suggestions.
cheers,
frank grimes
p.s. why would adobe make updateAfterEvent() only work with specific event types?
Question About Custom Events Dispatching
Hi,
Just a quick question to put my mind at rest about custom event dispatching in flash.
say i have a class and i import flash.events.eventdispatcher.
then at some stage in my class I say
this.dispatchEvent(MyEvent)
I get a "call to possibly undefined method" error.
Now if in my class I say
someObj.dispatchEvent the error goes away and the event dispatches fine.
Could somebody please explain this to me?
Making Events For Custom Class
I'm working on a custom class that handles synching of externally loaded audio and some timeline animations -- nothing high-paced and millisecond timed. I've got it all working fairly well, but I'm wondering how my custom SyncAnimation class can tell others that it is done? In other words, how can I have it tell others when it gets to the last frame that it has reached the last frame?
I know how to use the EventDispatcher class and can dispatch events. If I initilize the SyncAnimation class as a Dispatcher I guess I could put
dispatchEvent({type:"onComplete",target:this});
on the last frame. Or I could start a loop in the class that just keeps checking if it is on the last frame and when it is dispatch the event. Or perhaps something else that I haven't thought of?
I want to keep as much code in the class as possible, because various developers will be creating the timeline animations and the fewer things on the timeline that could be messed up the better.
Anybody have any clever ways they've dealt with this before?
Custom Events And Listeners Between Classes
I've got a project I've been working on for weeks that I'm having yet another problem with. I'm trying to learn AS3 which is why it's taking so long but that's not important for this post.
I wanted to create a custom event class so that I could make sure the event does not interfere with other "COMPLETE" events that are being passed between classes. In other words, I have a few things that need to complete prior to a function being called... one is some XML being loaded and another is a font loaded. So, I thought I would create a custom FontLoaded class that extends Event and make the type something like "FontLoadedEvent.LOADED". That way I could listen for the XML "Event.COMPLETE" and this font event also.
Please tell me if I'm going down the wrong path here but I don't seem to be getting the dispatched event for my new custom event. Also, how does one detect if it's being dispatched other than if the eventListener is fired? Any other ways to test this?
Events Bubbling Out Of Custom Classes?
Okay, I'm trying to create a job queue type of system that uses event bubbling so that events can be dispatched from multiple locations and bubble up to a front controller.
For some reason my EventHandler is never being called:
OUTPUT:
DataPack Constructed
Custom Event Constructed
EventTransporter Constructed
Dispatching event type: _dataevent
Does anyone see anything terribly wrong here?
TestEvents.as
Code:
package {
import flash.display.Sprite;
public class TestEvents extends Sprite
{
public function TestEvents()
{
addEventListener(CustomEvent.DATA_EVENT, onCustomEvent);
var myCaller:EventCaller = new EventCaller();
var myData:DataPack = new DataPack([1,2,3,4,5]);
var event:CustomEvent = new CustomEvent(CustomEvent.DATA_EVENT, myData);
var holder:EventTransporter = new EventTransporter(event);
myCaller.callEvent(holder);
}
private function onCustomEvent(event:CustomEvent):void
{
trace("onCustomEvent data: "+event.data);
}
}
}
DataPack.as
Code:
package
{
public class DataPack
{
private var _stuff:Array;
public function DataPack(ary:Array)
{
trace("DataPack Constructed");
_stuff = ary;
}
public function get stuff():Array { return _stuff }
}
}
EventCaller.as
Code:
package
{
import flash.events.EventDispatcher;
[Event(name="_dataevent", type="CustomEvent")]
public class EventCaller extends EventDispatcher
{
public function EventCaller() {}
public function callEvent(holder:EventTransporter):void
{
trace("Dispatching event type: "+holder.event.type);
dispatchEvent(holder.event);
}
}
}
EventTransporter.as
Code:
package
{
public class EventTransporter
{
private var _event:CustomEvent;
public function EventTransporter(event:CustomEvent)
{
trace("EventTransporter Constructed");
_event = event;
}
public function get event():CustomEvent { return _event }
}
}
CustomEvent.as
Code:
package
{
import flash.events.Event;
public class CustomEvent extends Event
{
public static const DATA_EVENT:String = "_dataevent";
private var _data:DataPack;
public function CustomEvent(type:String, data:DataPack)
{
trace("Custom Event Constructed");
super(type, true);
_data = data;
}
public function get data():DataPack { return _data }
}
}
Custom Events And Objects-by-reference
Hello all, I have successfully (!) created myself a custom event dispatcher. Hopefully I won't need to paste any code, and I can just say that I have an Inventory class that contains an array filled with items (from an Item class). When you click an Item in the inventory, it dispatches an event containing itself, to the Inventory class so that I can do stuff with it (equip it, sell it, whatever). Right now all I'm trying to do is have the item that you clicked, display itself in a "currently equipped" object. Is there any way that I can dispatch a reference to the clicked item, and not dispatch the item itself? I ask this because when I put the dispatched item into the "currently equipped" item, it actually puts the item itself FROM the inventory and up into the currently equipped box. I just want to basically copy the item by reference and not effect it's original values. Let me know if this doesn't make sense, and thanks in advance.
Custom Events / Multiple Classes
Alright, so I guess my understanding of custom events isn't that great. For discussion sake, let's say I have three classes: base, object, custom eventdispatcher. The objects is an animation that uses the Tweener class. Once the animation is complete, it dispatches a custom event, "ANIM_DONE." Now, my understanding of events is that it should "bubble up" until reaches it's listener, which I have setup in the base class. But I am getting nothing, which tells me it not making its way up to the base class. Here's the code:
Base
Code:
package{
import flash.events.*;
import flash.display.*;
import Animation;
public class Base extends MovieClip{
public function Base(){
var anim:Animation = new Animation();
var customEvent:CustomEvent = new CustomEvent();
customEvent.addEventListener(customEvent.ANIM_DONE, nextAnimation);
}
public function nextStep(e:Event){
trace("nextStep")
}
}
}
Object
Code:
package{
import flash.events.*;
import flash.display.*;
public class Animation extends MovieClip{
var ce:CustomEvent = new CustomEvent();
public function Animation(){
Tweener.addTween(logo, {alpha:1, time:.5, delay:5.7, transition:"easeInQuart", onComplete:ce.animFinished});
}
}
}
CustomEvent
Code:
package{
import flash.events.*;
public class CustomEvent extends EventDispatcher{
public static const ANIM_DONE:String = "animDone";
public function animFinished():void{
trace("animFinished");
dispatchEvent(new Event(CustomEvent.ANIM_DONE));
}
}
}
What am I missing? Thanks in advance.
Listening For Events With Custom UI Components
hi all,
to better learn the finer points of designing UI components, i'm trying to develop a simple accumulator. you know, a list on the left side, a list on the right side, and some buttons in the middle to move crap back and forth... i'm sure components like this are available already, but like i said, i'm doing it for the educational value.
anyway, i've set up Accumulator.fla like so. one layer (UI) contains a "to" List, a "from" List, an "add" Button, a "remove" Button, and a "bounding box" MovieClip. the other layer (Actions) contains the script to add a few elements to the "from" List, just so i have something to work with.
i've also set up Accumulator.as with all of the class initialization stuff (constructor, init() method, size() method, etc...) as needed.
so, when i fire up the movie, the UI controls work properly (Lists are populated, Buttons are clickable, etc...), and all of the trace statements i put in my Accumulator class are showing up. during the initialization of the Accumulator class, i'm trying to add a listener to the "Add" button. here's the trouble... the "click" event never seems to get trapped in this case. however, if i add a listener on the "Add" button in the Actions layer instead, everything works fine.
anyone have any ideas what might be going wrong? the goal here is to be able to add the listener on the "Add" button from inside the Accumulator class, rather than having to put listening code on in the Actions layer outside the Accumulator class. that way, everything is encapsulated in a nice neat little package. is there a better way to approach this?
thanks in advance.
Custom Events For Built-in Objects?
Is there any way to code custom events into built in objects?
A simple example of what I want to do is something like this:
create a method of the MovieClip object called "fade()"
at the end of the fade method (which would gradually drop the alpha), I want it to trigger an onFadeOut event. How do I do this?
Aaron
Adding Custom Events To URLLoader
I made a custom event so that I can pass params to my listener. Thing is I want to add my Custom event to the URLLoader so I can have it dispatch it when it is finished loading. Is there any way to do this??
There anyway to change what the URLLoader dispatches?
Example
Code:
var loader:URLLoader = new URLLoader()
loader.addEventListener(CustomEvent.CUSTOM, blah, [params])
loader.load(blahablhablah)
Understandig Problem With Custom Events
hi all,
i tried to build my first custon event after reading through some stuff but somehow i need a bit help on this example:
my first class looks like this:
Code:
public class subnaviBuilder extends naviBuilder {
public static var CLEAR:String = "clear";
public function subnaviBuilder () {
dispatchEvent(new Event(subnaviBuilder.CLEAR));
}
}
the class that should listen to the event looks like this:
Code:
public class VideoPlayer extends subnaviBuilder {
public function VideoPlayer() {
vid = new Video(320, 240);
nc = new NetConnection();
nc.connect(null);
ns = new NetStream(nc);
ns.bufferTime = 5;
ns.addEventListener(NetStatusEvent.NET_STATUS, onStatusEvent);
this.addEventListener(subnaviBuilder.CLEAR, closeNSBtn);
addChild(vid);
vid.attachNetStream(ns);
vid.visible = false;
ns.play("myflv.flv");
}
public function closeNSBtn(e:Event):void {
trace("button click:");
}
}
the event is not fired can anyone help me understanding it?
thanks a lot
|