如何从加载到 Flex 应用程序(使用 SWFLoader)的 SWF 文件中引发事件?
我希望能够检测到
a) when a button is pressed
b) when the animation ends
如何从加载到 Flex 应用程序(使用 SWFLoader)的 SWF 文件中引发事件?
我希望能够检测到
a) when a button is pressed
b) when the animation ends
你需要做两件事:
从您的主应用程序监听事件。我认为您应该能够在 SWFLoader 实例的 content 属性上执行此操作。
mySWFLoader.content.addEventListener("myEvent", myEventHandler);
我采取了一种更懒惰的方法来在 Flash 中引发事件
<mx:SWFLoader source="homeanimations/tired.swf" id="swfTired" complete="swfTiredLoaded(event)" />
private function swfTiredLoaded(event:Event): void {
mySWFLoader.content.addEventListener("continueClicked", continueClickedHandler);
}
dispatchEvent(new Event("continueClicked", true, true));
我相信这是因为您将创建两个单独的自定义事件类,一个在 Flash 中,另一个在 Flex 中。Flex 可能无法理解从 Flash 调度一个 EV_NOTIFY.ANIMATION_ENDED,因为它有自己的 EV_NOTIFY.ANIMATION_ENDED 版本。
As an adjunct to the answer by Christophe Herreman, and in case you were wondering, here is a way of making your own events...
package yourpackage.events
{
import flash.events.Event;
[Event(name="EV_Notify", type="yourpackage.events.EV_Notify")]
public class EV_Notify extends Event
{
public function EV_Notify(bubbles:Boolean=true, cancelable:Boolean=false)
{
super("EV_Notify", bubbles, cancelable);
}
}
}
I have taken the liberty of setting the default value of bubbles
to true and passing the custom event type to the super constructor by default, so you can then just say...
dispatchEvent(new EV_Notify());
In your particular case I doubt there are times when you would not want your event to bubble.
The prefix EV_
on the name is my own convention for events so I can easily find them in the code completion popups, you'll obviously pick your own name.
For the two cases you cite you can either have two events and listen for both of them, or add a property to the event which says what just happened, which is the approach which is taken by controls like Alert
...
package yourpackage.events
{
import flash.events.Event;
[Event(name="EV_Notify", type="yourpackage.events.EV_Notify")]
public class EV_Notify extends Event
{
public static var BUTTON_PRESSED:int = 1;
public static var ANIMATION_ENDED:int = 2;
public var whatHappened:int;
public function EV_Notify(whatHappened:int, bubbles:Boolean=true, cancelable:Boolean=false)
{
this.whatHappened = whatHappened;
super("EV_Notify", bubbles, cancelable);
}
}
}
then you call it as follows...
dispatchEvent(new EV_Notify(EV_NOTIFY.ANIMATION_ENDED));
you can then inspect the whatHappened field in your event handler.
private function handleNotify(ev:EV_Notify):void
{
if (ev.whatHappened == EV_Notify.ANIMATION_ENDED)
{
// do something
}
else if (ev.whatHappened == EV_Notify.BUTTON_PRESSED)
{
// do something else
}
etc...
}
HTH
我无法使用最后一种方法(使用 Flash CS4 和 Flex 3)。我将 dispatchEvent 调用放在 Flash 动画的最后一帧中,但无法在 Flex 中获取。
我使用了一个计数器变量并递增,直到我使用 ENTER_FRAME 事件达到已知的最后一帧编号 - 我可以使用几乎相同的代码来获取它。
如果我可以选择这个,那为什么我不能选择自定义事件呢?