改變

2014-07-19 11 views
2

進出口工作在裝載谷歌地圖點播,我的網站使用該代碼的GoogleMap回調的這個值:改變

var googleMaps = document.createElement("script"); 
    googleMaps.type = "text/javascript"; 
    googleMaps.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&" + 
    "callback=googlemapready"; 

問題是,無論我做什麼,回調爲「window.googlemapready」執行,有什麼辦法可以將它設置爲不同對象的方法?這是沒有污染全球命名空間,我知道我可以在一個函數中包裝上面的代碼,並設置window.googlemapready =東西...

+0

使用jsapi的加載器:http://stackoverflow.com/questions/5296115/can-you-load-google-maps-api-v3-via-google-ajax-api-loader –

+0

據我瞭解這不會做,因爲我不僅要動態地初始化地圖,而且還會根據請求動態地將非常googlemap腳本插入到我的頁面中(以便在請求使用地圖之前未下載它)。 – user3561092

+0

maps-API會在加載時加載(jsapi必須預先加載) –

回答

0

基本上回調一定是一個函數,當你在全球範圍內這是谷歌運行回調的地方)。

API使用eval執行回調,因此該過程是這樣的:

//the global callback 
function bar(){ alert('callback executed');} 

//string provided as callback 
callbackname='bar' ; 

//execute it 
eval('window.'+callbackname+'()') ; 

當你看看EVAL-部分,應該可以運行一個沒有定義的全局函數,例如作爲對象的屬性:

//a global object with a method 
foo={bar:function(){ alert('callback executed too');}}; 

//string provided as callback 
othercallbackname='foo.bar'; 

//execute it 
eval('window.'+othercallbackname+'()'); 

...它的工作原理(也與地圖API)。

問題:您仍然需要一個全局的東西(在這種情況下爲foo)。

但它不是一個真正的問題,當你與谷歌的API的工作會有你無法擺脫的至少1個全局對象:google

所以:定義回調作爲全球google財產-目的。

你可能會問如何設置,當你沒有加載API但谷歌的性質:它定義你自己的,你加載API之前:

window.google={bar:function(){/*do something*/}}; 

..then使用加載API :callback=google.bar

樣品的實現(適用於多呼叫):

//create maps of elements with className map 
document.addEventListener('click',function(e){ 
    var node=e.target,callback,script,execCallbacks; 

    //check the class 
    if(node.className==='map'){ 
    //assign a new class to prevent from further clicks 
    node.className='mapped'; 

    //when window.google isn't available, create it 
    if(!window.google){ 
     window.google={}; 
    } 

    //we will store the callbacks in an array 
    if(!window.google.callbacks){ 
     window.google.callbacks=[]; 
    } 
    //function that executes the callbacks 
    if(!window.google.execCallbacks){ 
     window.google.execCallbacks=function(){ 
     while(this.callbacks.length){ 
      this.callbacks.shift()(); 
     } 
     }; 
    } 

    //define the callback(creates a simple map) 
    callback=function(){ 
     new google.maps.Map(node, 
          {zoom:1, 
          center:new google.maps.LatLng(0,0) 
          }); 
    }; 

    //google.maps isn't loaded yet 
    if(!window.google.maps){ 
     //push the callback to the callbacks 
     window.google.callbacks.push(callback); 
     //load the API 
     script=document.createElement('script'); 
     script.src="https://maps.googleapis.com/maps/api/js?v=3&" + 
        "callback=google.execCallbacks"; 
     document.getElementsByTagName('script')[0].parentNode.appendChild(script); 
    } 
    //API is already loaded, run the callback directly 
    else{ 
     callback(); 
    } 

    } 
}); 

演示:http://jsfiddle.net/doktormolle/gH8FR/

+0

非常聰明,那應該是我正在尋找的。 – user3561092