事件发生后退出功能
我想要有自己的初始化函数,并且我希望它仅在 onload 事件之后退出,我该怎么办?
var qqq=0;
function init(){
var requestClient= Ti.Network.createHTTPClient();
requestClient.open('GET','https://mysite.com/api/123/id/5/friends');
requestClient.onload = function() {
alert('loaded');
};
requestClient.send();
};
init();
alert(qqq);
I want to have my own initialization function, and I want it exit only after onload event, what can I do for it?
var qqq=0;
function init(){
var requestClient= Ti.Network.createHTTPClient();
requestClient.open('GET','https://mysite.com/api/123/id/5/friends');
requestClient.onload = function() {
alert('loaded');
};
requestClient.send();
};
init();
alert(qqq);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,您可以通过使请求同步而不是异步来做到这一点。这会对用户的浏览体验产生令人不快的副作用,往往会在请求期间锁定内容,但是如果您设置
open
的第三个参数为false
,它将使其同步而不是异步:同步请求将带来JavaScript执行在页面上(位于至少,在许多浏览器中不仅仅是 JavaScript)会突然停止,直到网络操作完成。
但是通常的做法是让您的
init
接受您在onload
处理程序中调用的回调,因为这可以带来更好的用户体验:有效的网络编程就是拥抱它的事件驱动的本质。我强烈推荐第二个例子。
Well, you can do that, by making the request synchronous instead of asynchronous. This has unpleasant side-effects on the user's browsing experience, tending to lock things up during the request, but if you set
open
's third argument tofalse
, it will make it synchronous instead of asynchronous:A synchronous request will bring the JavaScript execution on the page (at least, and in many browsers rather more than just the JavaScript) to a screeching halt until the network operation completes.
But the usual practice is to have your
init
accept a callback you call from within theonload
handler, as this makes for a much better UX:Effective web programming is about embracing the event-driven nature of it. I'd strongly recommend the second example.