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

标签 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();  

    };

})();

我在如下 View 中调用此函数:

(function() {

    main.ui.createAlbumsWindow = function(_args) {

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

        var albums = main.model.getAlbums();

        alert(albums);

        return albumsWindow;
    };
})();

然而,对模型的调用(使用 HTTP 获取一些数据)似乎并不等待响应。在我发出警报时的 View 中,它还没有收到来自模型的数据。我如何以最佳实践方式做到这一点?

提前致谢

最佳答案

好的,

像这样,

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);
});

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

干杯。

关于javascript - Titanium mvc - 调用函数并等待结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8461299/

相关文章:

java - 如何避免静态资源请求被路由到拦截器?

c# - Dal(带有 Entity Framework )和模型层进入 MVC

javascript - 从左侧滑入内容,覆盖现有内容并插入侧边栏

php - 如果是 iPad/iPhone,则不显示此信息

javascript - TypeScript 中的 `const func: (num: number) => string = String;` 是什么意思?

iphone - 如何触发uiview动画再次炒锅

iphone - iPhone 上的蓝牙链接 key

objective-c - 为什么 UIImageView 拥有 UIImage。它是否违反了 MVC 原则?

javascript - 当另一个复选框被重叠选中时取消全部选中/选中一个复选框

javascript - 我的 AngularJS Spinner 指令失败