Titanium mvc - 调用函数并等待结果

1 javascript iphone model-view-controller titanium titanium-mobile

我目前正在制作我的第一个Titanium iPhone应用程序.

在我得到的模型中:

(function() {   
    main.model = {};

    main.model.getAlbums = function(_args) {

        var loader = Titanium.Network.createHTTPClient();  
        loader.open("GET", "http://someurl.json"); 

        // Runs the function when the data is ready for us to process 
        loader.onload = function() { 
            // Evaluate the JSON  
            var albums = eval('('+this.responseText+')');  
            //alert(albums.length);
            return albums;
        }; 

        // Send the HTTP request  
        loader.send();  

    };

})();
Run Code Online (Sandbox Code Playgroud)

我在以下视图中调用此函数:

(function() {

    main.ui.createAlbumsWindow = function(_args) {

        var albumsWindow = Titanium.UI.createWindow({  
            title:'Albums',
            backgroundColor:'#000'
        });

        var albums = main.model.getAlbums();

        alert(albums);

        return albumsWindow;
    };
})();
Run Code Online (Sandbox Code Playgroud)

然而,似乎对模型的调用(使用HTTP获取一些数据)不等待响应.在我执行警报的视图中,它还没有收到模型中的数据.我该如何以最佳实践方式做到这一点?

提前致谢

The*_*ero 6

好,

像这样的东西,

function foo(arg1, callback){
     arg1 += 10;
     ....
     ... Your web service code
     ....
     callback(arg1); // you can have your response instead of arg1
}

you will call this function like this,

foo (arg1, function(returnedParameter){
     alert(returnedParameter); // here you will get your response which was returned in   above function using this line .... callback(arg1);
});
Run Code Online (Sandbox Code Playgroud)

所以这里arg1是参数(简单参数,如整数,字符串等......),第二个参数是你的回调函数.

干杯.