Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
  };
  
}
like image 284
meow Avatar asked Dec 06 '10 18:12

meow


1 Answers

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");
   }
});
like image 161
Juan Mendes Avatar answered Nov 08 '22 06:11

Juan Mendes