我正在构建一个 javascript 对象,它主要应该在处理其上的任何其他功能之前发送身份验证 ajax 请求。
示例:
hello={
say:function(txt){
alert(txt);
},
auth:function(){
... ajax ...
}
}
hello.say("hello world!");
在成功获取身份验证 ajax 请求之前,不应触发警报。这就像将任何函数排队到对象中,直到初始化完成。
附注当页面完全加载时,应该自动触发身份验证。
- 编辑
尝试使用 SLAks 方法:
functionQueue = [];
function exec(func) {
if (functionQueue){
functionQueue.push(func);
}else{
func();
}
}
hello={
say:function(txt){
alert(txt);
},
auth:function(){
ajax.post("http://www.hello.com",function(resp){
var queue = functionQueue;
functionQueue = false; //Prevent re-entrancy
for (var i = 0; i < queue.length; i++){
queue[i]();
}
});
}
}
function start(){
hello.auth();
}
window.addEventListener("load", start, false);
hello.say("hello world!");
非常感谢您的帮助。
谢谢!
最佳答案
创建一个要执行的函数数组,如果请求尚未完成,则将每个函数推送到数组中,然后在 AJAX 请求完成时循环执行数组中的函数。
例如:
var functionQueue = [];
function exec(func) {
if (functionQueue)
functionQueue.push(func);
else //AJAX request already finished
func();
}
$.ajax({
...
success: function(...) {
...
var queue = functionQueue;
functionQueue = false; //Prevent re-entrancy
for (var i = 0; i < queue.length; i++)
queue[i]();
}
});
编辑:Demo
第二nd编辑:要在对象内使用exec
,保留this
可能很有用:
var functionQueue = [];
function exec(func, context) {
if (functionQueue){
functionQueue.push(function() { func.call(context); });
} else {
func.call(context);
}
}
var hello = {
say: function(txt){
exec(function() {
alert(txt); //this still works
}, this);
},
auth: function(){
$.get("/echo/json/", function(resp){
var queue = functionQueue;
functionQueue = false; //Prevent re-entrancy
for (var i = 0; i < queue.length; i++){
queue[i]();
}
});
}
};
hello.say("hello world!");
hello.auth();
您可能想将队列放入对象中:
var hello = {
functionQueue: [],
exec: function(func) {
if (this.functionQueue){
this.functionQueue.push(func);
} else {
func.call(this);
}
},
say: function(txt){
this.exec(function() {
alert(txt); //this still works
});
},
auth: function(){
var me = this;
$.get("/echo/json/", function(resp){
alert('AJAX finished!');
var queue = me.functionQueue;
functionQueue = false; //Prevent re-entrancy
for (var i = 0; i < queue.length; i++){
queue[i].call(me);
}
});
}
};
hello.say("hello world!");
hello.auth();
关于javascript - 如何在 JS 类中对函数进行排队,直到完成基本的 ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4514542/