开发者

Custom Event Not Captured- why?

开发者 https://www.devze.com 2022-12-17 01:39 出处:网络
I am having a problem where I dispatch a custom event but the listener does not receive it (i.e. myHandler() in the code below).If I put everything in one mxml file, it works.When I separate the respo

I am having a problem where I dispatch a custom event but the listener does not receive it (i.e. myHandler() in the code below). If I put everything in one mxml file, it works. When I separate the responsibilities in to separate classes, it fails. It is not clear to me what I am missing.

Any help you be appreciated.

Here is my code (update() in ViewModel.as is the entry point):

ChangeEvent.as

import flash.events.Event;

public class ChangeEvent extends Event
{
    public function ChangeEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
    {
        super(type, bubbles, cancelable);

        // Set the new property.
        this.isEnabled = isEnabled;
    }

    // Define static constant.
    public static const ENABLE_CHANGED:String = "enableChanged";

    // Define a public variable to hold the state of the enable property.
    public var isEnabled:Boolean;

    // Override the inherited clone() method.
    override public function clone():Event {
        return new ChangeEvent(type, isEnabled);
    }       

}

Model.as

public class Model extends EventDispatcher
{
    private function TriggerEvent():void
    {
        var eventObj:ChangeEvent = new ChangeEvent(ChangeEvent.ENABLE_CHANGED);
        dispatchEvent(eventObj);
    }
}

ViewModel.as

public class ViewMode开发者_高级运维l
{
    import mx.controls.Alert;
    import ChangeEvent;

    private var model:Model;

    public function ViewModel()
    {       
        model = new Model();

        addEventListener(ChangeEvent.ENABLE_CHANGED, myHandler);
    }

    public function update():void {
        model.LoadData();
    }

    private function myHandler(event:Event):void {

        Alert.show("An event occurred.");                   
    }   
}

Do I have to 'register' the event in ViewModel.as similar to the metadata tag in mxml? e.g. [Event(name="enableChange", type="ChangeEvent")]


You have to add the event listener on the model object (since it is the one dispatching the event).

model = new Model();
model.addEventListener(ChangeEvent.ENABLE_CHANGED, myHandler);

Hope that helps.

0

精彩评论

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

关注公众号