TitaniumのaddEventListenerについて再び

TitaniumのaddEventListenerで同じイベントに登録した処理は順番に同期実行される。
Firefoxなどのブラウザ(ただしIE除く。IE9は不明)の実装でも同じ挙動になるので、これはこの通り動くと期待して間違いない挙動のようだ。

ただし処理内に別の非同期処理がある場合、その処理は非同期で実行され、次の順番の処理がその処理を待たずに実行される。

app.js

検証のためのサンプルコード。

Ti.App.addEventListener("custom", function(){ Ti.API.info("1st")});

Ti.App.addEventListener("custom", function(){ 
        a = new Date()
        while ((new Date()) - a < 3000) {
            // 時間のかかる処理でも待ってもらえる
        }
        Ti.API.info("2nd with sleep 3sec")
});

Ti.App.addEventListener("custom", function(){ 
    var xhr = Titanium.Network.createHTTPClient();
    xhr.open('GET','http://www.google.com/');
    xhr.onload = function(){
		// 非同期処理になるので4thに待ってもらえない
        Ti.API.info("3rd with async http")
    };
    xhr.send();
});

Ti.App.addEventListener("custom", function(){ Ti.API.info("4th")});

Ti.App.fireEvent("custom")

// fireEventは非同期なので以下の処理が先に走る
Ti.API.info("5th after fireEvent")
実行結果
[INFO] 5th after fireEvent
[INFO] 1st
[INFO] 2nd with sleep 3sec
[INFO] 4th
[INFO] 3rd with async http

この挙動はイベントのテストに役立ちそうだ。