views:

114

answers:

2

Hi there,

I would like to dispatch an event from my class along with a url.

I know that I can do the following:

import flash.events.EventDispatcher;

private function thumbClick(e:MouseEvent):void
{
   dispatchEvent(new Event("clicked"));
}

But I don't know how I would send params along with the event...?

Also, in my main app runner, I try:

var my_ev:Event = new Event("clickedImage");
my_ev.hasOwnProperty(e.currentTarget.link);
dispatchEvent(my_ev);

...but I'm not sure that this would be the correct syntax.

Thanks for any help, jml

+1  A: 

I just make a custom event class.

import flash.events.Event;  


public class ThumbnailEvent extends Event
{
    public static var THUMB_CLICKED:String = "thumbClicked";
    public var url:String;

    public function ThumbnailEvent (type:String,url:String)
    {
              super(type);
              this.url = url
    }
}

and then use it like:

var thumbEvent:ThumbnailEvent = new ThumbnailEvent(ThumbnailEvent.THUMB_CLICKED,"myURL");
dispatchEvent(thumbEvent);
Allan
Excellent. Thanks for the help! I didn't realize that Events could be used to pack things together as such... Should have.
jml
no worries :) and yes follow Joel's way of doing it, i just get a bit lazy sometimes.. haha
Allan
+3  A: 

Allan is correct, you will want to make a custom event. Couple of things to note:

import flash.events.Event;  

public class ThumbnailEvent extends Event
{
    public static var THUMB_CLICKED:String = "thumbClicked";

    private var _url:String;
    public function get url():String { return _url }

    public function ThumbnailEvent (type:String, url:String, bubbles:Boolean=false, cancelable:Boolean=false)
    {
        super(type,bubbles,cancelable);
        _url = url
    }

    override public function clone():Event
    {
        return new ThumbnailEvent(type, url, bubbles, cancelable);
    }
}

Custom events need to always override clone. If the event is bubbled or relayed in anyway it needs this method. Custom properties should be private with a read-only getter. This is a standard convention to prevent the alteration of properties throughout the life of the event.

Using this approach would change your code to:

private function thumbClick(e:MouseEvent):void
{
   dispatchEvent(new ThumbnailEvent(ThumbnailEvent.THUMB_CLICKED, myUrlString));
}

//elsewhere

addEventListener(ThumbnailEvent.THUMB_CLICKED, thumbClickedHandler);

private function thumbClickedHandler(event:ThumbnailEvent):void
{
    var link:String = event.url;
}

Custom Event tutorial at adobe.com

Joel Hooks
Thanks very much for including these details, Joel.
jml