-
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
-
A few things.
First, if the Duck.as file for the Duck class is in the same folder as the Flash File, then you need not import it.
Secondly, the above code doesnt actually create an instance of the Duck class. It only says, the the variable 'dd' at some point will be assigned a value which will be of type 'Duck'.
And to answer your question. You need to open up the Duck.as file and make it observable by using the mx.events.EventDispatcher mixin, something like this:
Code:
import mx.events.EventDispatcher;
class Duck
{
//mix-ins
private var dispatchEvent:Function
public var addEventListener:Function
public var removeEventListener:Function
function Duck()
{
EventDispatcher.initialize(this);
this.startTalking();
}
private function startTalking():Void
{
//start it talking, play a sound or whatever
_global["setTimeout"](this,"finishedTalking",2000);
}
private function finishedTalking():Void
{
this.dispatchEvent(new DuckEvent(DuckEvent.FINISHED_TALKING))
}
}
Then i recommend you get into the habit of creating your own event classes, for example:
[code]
class DuckEvent
{
//enums
public static var FINISHED_TALKING:String = "finishedTalking"
function DuckEvent(type:String)
{
this._type=type;
}
public function get type():String
{
return this._type;
}
}
Then you can use this class as follows:
Code:
import mx.utils.Delegate;
var dd:Duck = new Duck();
duck.addEventListener(DuckEvent.FINISHED_TALKING,Delegate.create(this,this.duckFinishedTalking));
function duckFinishedTalking(evt:DuckEvent):void
{
trace("the duck finished talking");
}
-
My Output window says this._type does not exist
-
My Duck class extends MovieClip - could this interfere because I think MovieClip defines addEventListener
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|