开发者

Dispatch an event from a class that inherits from EventDispatcher

I've got a class that extends EventDispatcher.

What I want to do is to dispatch the click event when the component is clicked. (The class is essentially some text in a textfield that needs to be able to do certain things, and it needs to be able to respond to a click). Sounds easy enough... I want the event dispatched when that portion of the text is clicked. But uh...how? it's not like a button where I can just go

myButton.addEventListener(MouseEvent.CLICK, myClickHandler);

That's clear, because some component is going to be listening for the Click event dispatc开发者_运维技巧hed when myButton is clicked. It is built into the AS3 framework that a button knows how to listen for a click event.

After the import statements I've got:

[Event(name="click" type="mx.events.Event")]

How do I dispatch the event when the component is clicked, when the component doesn't yet know how to respond to a click event? I've tried adding an event listener in the textfield which contains this custom class of text, but nothing's happening because the Click event hasn't been dispatched.


You can create your own click event and dispatch it. You can do that also to dispatch clicks on objects where no user ever have clicked :D

Try this:

var mEvent:MouseEvent = new MouseEvent(MouseEvent.CLICK, [HERE MORE PARAMS BY YOU]);
yourObject.dispatchEvent(mEvent);

Now, you will recieve Click Events from yourObject.


Let's say your class consists TextField tf. Then

public function YourClass():void { //Constructor
{
//intialize Something 
//initialize tf
tf.addEventListener(MouseEvent.CLICK, onClick);
...
}
...
private function onClick(e:MouseEvent):void {
  this.dispatchEvent(new MouseEvent(MouseEvent.CLICK));
}


OK, I tried this in the constructor:

    var mEvent:MouseEvent = new MouseEvent(MouseEvent.CLICK, true, false);
this.dispatchEvent(mEvent);

Then, in the containing textfield, while iterating through these objects (each of which is called cp), I did this:

                cp.addEventListener(MouseEvent.CLICK, mouseClickHandler);

Finally the mouseClickHandler:

    private function mouseClickHandler(event:MouseEvent):void 
    {
        trace("Clicked!!!!!!!!!!!");
    }

Running in debug mode I get nada. Nunca. Niente. Nuttin'. Which is to say: no trace of being clicked. Did I do something wrong?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜