2012/4/23

AS3 try catch on EventDispatcher.dispatchEvent()

當 try catch 遇到 EventDispatcher

public function TestClass() 
{
    try {
        eventDispatch().dispatchEvent(new Event("TEST"));
    }
    catch (err:Error)
    {
        trace(err);
    }
}
public function eventDispatch():EventDispatcher{
    var ed:EventDispatcher = new EventDispatcher();
    ed.addEventListener("TEST",crashFunction);
    return ed;
}
public function crashFunction(e:Event = null):void {
    var a:Array ;
    a.concat();
}

請問上面的程式會 ?
1. 觸發 trace
2 .進入執行階段錯誤

以下內容要按讚才顯示  [讚]

























答案是2. 會進入執行階段錯誤

我另外測了callback

public function TestClass() 
{
    try {
        crashCallback(crashFunction);
    }
    catch (err:Error)
    {
        trace(err);
    }
}
public function crashCallback(f:Function):void {
    f();
}
public function crashFunction(e:Event = null):void {
    var a:Array ;
    a.concat();
}


結果是 callback 會觸發 trace

於是自己做了一個簡單版的EventDispatcher

public class MyEventDispatcher 
{
    public var functionArray:Array = [];
    public function addEventListener(f:Function):void {
        functionArray.push(f);
    }
    public function dispatchEvent():void {
        for each(var f:Function in functionArray)
            f();
    }
}

public class TestClass extends Sprite
{
    public function TestClass() 
    {
        try {
            eventDispatch().dispatchEvent();
        }
        catch (err:Error)
        {
            trace(err);
        }
    }
    public function eventDispatch():MyEventDispatcher{
        var ed:MyEventDispatcher = new MyEventDispatcher();
        ed.addEventListener(crashFunction);
        return ed;
    }
    public function crashFunction(e:Event = null):void {
        var a:Array ;
        a.concat();
    }
}

結果也是觸發 trace

內建的 eventDispatcher 到底是.../]\?


沒有留言: