如何在 Flex 中分派具有动态内容的事件?
How to dispatch an event with dynamic content in Flex?
我经常需要发送带有 soem 自定义 String
文本的 flash.events.Event
,例如:
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
,但我不知道我是否会在这里滥用它。
要在您的事件中包含其他数据,请通过扩展 Event
(或 Event
的任何子 class)并添加您自己的自定义事件 class特性。例如:
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);
}
这不如使用自定义事件灵活,也更脆弱 class,但有时是一个快速简单的解决方案。
我经常需要发送带有 soem 自定义 String
文本的 flash.events.Event
,例如:
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
,但我不知道我是否会在这里滥用它。
要在您的事件中包含其他数据,请通过扩展 Event
(或 Event
的任何子 class)并添加您自己的自定义事件 class特性。例如:
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);
}
这不如使用自定义事件灵活,也更脆弱 class,但有时是一个快速简单的解决方案。