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

发布于 2024-12-20 20:31:43 字数 1094 浏览 1 评论 0原文

我目前正在制作我的第一个 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();  

    };

})();

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

(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 获取一些数据)似乎不会等待响应。在我执行警报时的视图中,它尚未收到来自模型的数据。我如何以最佳实践方式做到这一点?

提前致谢

I am currently in the process of making my first Titanium iPhone app.

In a model I got:

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

    };

})();

and I call this function in a view like:

(function() {

    main.ui.createAlbumsWindow = function(_args) {

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

        var albums = main.model.getAlbums();

        alert(albums);

        return albumsWindow;
    };
})();

however it seems like the call to the model (which fetches some data using HTTP) doesn't wait for a response. In the view when I do the alert it haven't received the data from the model yet. How do I do this in a best-practice way?

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

一袭水袖舞倾城 2024-12-27 20:31:43

好的,

类似这样,

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 是参数(简单参数,如整数、字符串等......),第二个参数是你的回调函数。

干杯。

OK,

Something like this,

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

so here arg1 is parameter (simple parameter like integer, string etc ... ) and second argument is your call back function.

Cheers.

旧街凉风 2024-12-27 20:31:43

您需要的是同步调用 Web 服务,以便它会等到您收到服务的响应。

要在java脚本中实现这一点,您必须将回调函数作为参数传递,并在回调函数中获取返回值,而不是通过return语句返回值。

实际上,您使用的编码风格对我来说是新的,因为我使用不同的编码风格。

但最重要的是你必须使用回调函数来检索值而不是 return 语句。尝试一下,如果您仍然遇到问题,请告诉我,我会尝试举一个例子。

What you need is Synchronous call to web service, so that it will wait till you get the response from the service.

To achieve this in java script you have to pass callback function as parameter and get the return value in callback function instead of returning value by return statement.

Actually coding style you are using is new for me because i am using different coding style.

But the main thing is you have to use call back function to retrieve value instead of return statement. Try this and if you still face the problem than tell me i will try to give an example.

淑女气质 2024-12-27 20:31:43

像零解释这样的回调方式已经很好地解释了,但是您也可以尝试使用事件来处理它。

(function() {

    main.ui.createAlbumsWindow = function(_args) {

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

        var status = new object(), // eventlistener
        got_a_valid_result = false;

        // catch result
        status.addEventListener('gotResult',function(e){
          alert(e.result);
          got_a_valid_result = true;
        });           

        // catch error
        status.addEventListener('error',function(e){
          alert("error occured: "+e.errorcode);
          git_a_valid_result = true;
        });

        var albums = main.model.getAlbums(status);

        // wait for result
        while (!got_a_valid_result){};
        return albumsWindow;
    };
})();

你的模型可能是这样的

main.model.getAlbums = function(status) {

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

        loader.onload = function() { 
            var albums = eval('('+this.responseText+')');  

            status.fireEvent('gotResult',{result:albums});
            return albums;
        }; 

        loader.onerror = function(e){
            status.fireEvent('error',{errorcode:"an error occured"});
        };

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

    };

the callback way like zero explained is nicely explained, but you could also try to get it handled with events.

(function() {

    main.ui.createAlbumsWindow = function(_args) {

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

        var status = new object(), // eventlistener
        got_a_valid_result = false;

        // catch result
        status.addEventListener('gotResult',function(e){
          alert(e.result);
          got_a_valid_result = true;
        });           

        // catch error
        status.addEventListener('error',function(e){
          alert("error occured: "+e.errorcode);
          git_a_valid_result = true;
        });

        var albums = main.model.getAlbums(status);

        // wait for result
        while (!got_a_valid_result){};
        return albumsWindow;
    };
})();

and your model may something like

main.model.getAlbums = function(status) {

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

        loader.onload = function() { 
            var albums = eval('('+this.responseText+')');  

            status.fireEvent('gotResult',{result:albums});
            return albums;
        }; 

        loader.onerror = function(e){
            status.fireEvent('error',{errorcode:"an error occured"});
        };

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

    };
你与昨日 2024-12-27 20:31:43

作为建议,尝试使用 JSON.parse 而不是 eval,因为使用 eval 存在风险,因为它运行所有 javascript 代码。

Just as a suggestion, try to use JSON.parse instead of eval as there are risks involved with using eval since it runs all javascript code.

方圜几里 2024-12-27 20:31:43

我认为零发布的解决方案可能更适合内存管理,但我不完全确定。如果您使用 eventListener,请注意以下事项
(请参阅https://wiki.appcelerator.org/display/guides /管理+内存+和+查找+泄漏

function doSomething(_event) {
    var foo = bar;
}
// adding this event listener causes a memory leak
// as references remain valid as long as the app is running
Ti.App.addEventListener('bad:idea', doSomething);

// you can plug this leak by removing the event listener, for example when the window is closed
thisWindow.addEventListener('close', function() {
// to remove an event listener, you must use the exact same function signature
// as when the listener was added
Ti.App.removeEventListener('bad:idea', doSomething);
});

I think that the solution The Zero posted is likely better for memory management, but I'm not totally sure. If you do and eventListener, be aware of the following
(see https://wiki.appcelerator.org/display/guides/Managing+Memory+and+Finding+Leaks)

function doSomething(_event) {
    var foo = bar;
}
// adding this event listener causes a memory leak
// as references remain valid as long as the app is running
Ti.App.addEventListener('bad:idea', doSomething);

// you can plug this leak by removing the event listener, for example when the window is closed
thisWindow.addEventListener('close', function() {
// to remove an event listener, you must use the exact same function signature
// as when the listener was added
Ti.App.removeEventListener('bad:idea', doSomething);
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文