Should DispatchEvent be the last statement of a function?

微笑、不失礼 提交于 2019-12-24 19:16:00

问题


Should dispatchEvent must be the last statement of any function ?


回答1:


When you call dispatchEvent, all handlers for that event are immediately called before the rest of the function body where dispatchEvent was called runs. Does that mean that you need to call dispatchEvent as the last thing in a function body? Only if the code that is after the dispatchEvent call somehow depends on something that will be adversely changed when the handlers run.




回答2:


Absolutely not, dispatchEvent() can be invoked at anywhere as you wish. What make you to ask this question?




回答3:


Nope

dispatchEvent will fire an event, and the corresponding event handler will be executed immediately after the dispatchEvent is invoked.

However, unlike a return, the remaining lines of code will be executed after the event handler is completely executed

Simple test:

//Movie clip (mClip1)

function buzz():void {
    trace("buzz:1");
    dispatchEvent(new Event("justAnotherEvent"));
    trace("buzz:2");
}


//on the stage,

mClip1.addEventListener("justAnotherEvent", ping);

function ping(e:Event):void {
    trace("ping");
}

Output:

buzz:1
ping
buzz:2

edit I KNOW that using a literal string instead of a const for the event type is a bad practice, but as I said, this is just a simple quick down and dirty test.



来源:https://stackoverflow.com/questions/8270725/should-dispatchevent-be-the-last-statement-of-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!