Javascript chaining to wait for pop up window to return
how can i get a chain of functions to execute sequentially, when one of it involves waiting for a popup window?
In the authBegin function below, I am popping up a window, which returns to the authBegin function when completed.
But the chaining is of course not waiting for that. How can i make it wait till the window comes back?
am.authUnlessCurrent().authBegin().collectData();
var authModule=function(){
this.authUnlessCurrent=function(){
alert("checks auth");
};
this.authBegin=function(){
window.oauth_success = function(userInfo) {
popupWin.close();
return this;
}
window.oauth_failure = function() {
popupWin.close();
return true;
}
popupWin = window.open('/auth/twitter');
};
this.collectData=function(){
alert("collect data");
return this;
};
}
Your auth begin method doesn't return anything. There's no way to chain from a call if it doesn't return anything. However, your real problem is the fact that you need to wait on an asynchronous action (the user to authorize something on your popup). Therefore, you can't chain the calls, since chained calls require a synchronous (blocking) flow. In other words, there is no way to make your code block until the user responds, then collect data synchronously. You have to use callbacks.
One of the things I love about JS is the ability to specify callbacks inline, which makes it almost look like the chaining style you're looking for
Here's a suggestion, with a simplified version of your code:
/**
* Initialize an authorization request
* @param {Function} callback method to be called when authentication is complete.
* Takes one parameter: {object} userInfo indicating success or null
* if not successful
*/
function authenticate(callback) {
window.oauth_success = function(userInfo) {
popupWin.close();
callback(userInfo);
}
window.oauth_failure = function() {
popupWin.close();
callback(null);
}
var popupWin = window.open('/auth/twitter');
};
}
authenticate(function(userInfo){
if (userInfo) {
console.log("User succesfully authenticated", userInfo);
} else {
console.log("User authentication failed");
}
});
链接地址: http://www.djcxy.com/p/49226.html
上一篇: 从master更新Git分支
下一篇: Javascript链接等待弹出窗口返回