2010-03-20 77 views
0

見例如:調用函數A(args)調用函數B(),然後調用函數A(args),該怎麼做?

<!DOCTYPE html> 
<html> 

    <head> 
     <title>language</title> 
     <script type="text/javascript" src="http://www.google.com/jsapi"> 
     </script> 
    </head> 

    <body> 

     <div id="language"></div> 

     <script type="text/javascript"> 

      var loaded = false; 

      function load_api() { 

       google.load("language", "1", { 
        "nocss": true, 
        "callback": function() { 
         loaded = true; 
         callback_to_caller(with_caller_agruments); 
         // how to call a function (with the same arguments) which called load_api() ??? 
         // case 1 should be: detect_language('testing'); 
       // case 2 should be: translate('some text');      
        } 
       }); 
      } 

      function detect_language(text) { 
       if (!loaded) { 
        load_api(); 
       } else { 
        // let's continue... believe that google.language is loaded & ready to use 
        google.language.detect(text, function(result) { 
         if (!result.error && result.language) { 
          document.getElementById('language').innerHTML = result.language; 
         } 
        }); 
       } 
      } 

      function translate(text) { 
       if (!loaded) { 
        load_api(); 
       } else { 
        // let's continue... 
       } 
      } 

      detect_language('testing'); // case 1 
      translate('some text'); // case 2 
     </script> 
    </body> 

</html> 

回答

1

您需要通過調用程序和參數load_api,否則怎麼會知道無關變量的值?

 function load_api(f, text) { 
     ... 

     function detect_language(text) { 
      if (!loaded) { 
       load_api(detect_language, text); // or use load_api(arguments.callee, text) 

然後你可以在回調中調用它們。

   "callback": function() { 
        loaded = true; 
        f(text); 

如果A是可變參數,你可以使用arguments變量和Function.apply

function A (x, y, z) { 
    B(A, arguments); // or B(A, [x, y, z]) 
} 
function B (f, arr) { 
    setTimeout(1000, function() { 
    f.apply(this, arr); 
    }); 
} 
+0

感謝您的解決方案。如果函數/調用者擁有不同數量的農場,該怎麼辦? – Ken 2010-03-20 15:58:26

+1

@Ken:查看更新。 – kennytm 2010-03-20 16:12:13

1

如果你打電話的google.load不止一次,它是足夠聰明,不包括腳本再次,但你的回調仍然會被調用。因此,你可以做:

function load_api(callback) { 

    google.load("language", "1", { 
     "nocss": true, 
     "callback": callback 
    }); 
} 

function detect_language(text) { 
    load_api(function() { 
     // let's continue... believe that google.language is loaded & ready to use 
     google.language.detect(text, function(result) { 
      if (!result.error && result.language) { 
       document.getElementById('language').innerHTML = result.language; 
      } 
     }); 
    }); 
} 

function translate(text) { 
     load_api(function() 
     { 
      // Do whatever you want, including using text. 
     }); 
} 

注意,因爲封路的工作,您可以自由使用該函數的參數在回調。但是您可能會發現在頁面加載時只有一個回調會更簡單,並且在回調完成之前隱藏任何翻譯控件。

相關問題