如何在Flex中调度包含动态内容的事件?

时间:2015-06-03 14:34:51

标签: actionscript-3 flex

我经常要求使用自定义flash.events.Event文字发送String,例如:

protected function mouseClicked(event:Event) {
     //here I'd want to notify anyone interested in the button click,
     //and also transfer the name of the button (or whatever) that was clicked - assume some dynamic value
     dispatchEvent(new Event("myMouseEvent"), button.name));
}

当然上述事件无效。但是有没有可用于此类事件的事件?也许是TextEvent,但我不知道我是否会在这里滥用它。

1 个答案:

答案 0 :(得分:2)

要在事件中包含其他数据,请通过扩展Event(或Event的任何子类)并添加自己的属性来创建自定义事件类。例如:

class NameEvent extends Event {
    public static const NAME_CLICK:String = "nameClick";
    public var name:String;
    public function NameEvent(type:String, name:String) {
        this.name = name;
        super(type);
    }
}

dispatchEvent(new NameEvent(NameEvent.NAME_CLICK, button.name));

请注意,您的事件类型字符串(在此示例中为“nameClick”)应该是全局唯一的,否则侦听器可能会将它们与其他事件类型混淆。例如,“click”已经预计为MouseEvent。我经常为自定义事件类型添加前缀,例如“NameEvent :: click”。

不需要创建自定义事件的另一个选项是依靠预期目标来获取其他数据。例如:

// dispatch a custom event from a Button
dispatchEvent(new Event("myClick"));

// handler for "myClick" events on the button
function myClicked(e:Event):void {
    var button:Button = e.target as Button;
    trace(button.name);
}

这不像使用自定义事件类那样灵活,也更脆弱,但有时候是一个快速简单的解决方案。