基本上回調一定是一個函數,當你在全球範圍內這是谷歌運行回調的地方)。
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/
使用jsapi的加載器:http://stackoverflow.com/questions/5296115/can-you-load-google-maps-api-v3-via-google-ajax-api-loader –
據我瞭解這不會做,因爲我不僅要動態地初始化地圖,而且還會根據請求動態地將非常googlemap腳本插入到我的頁面中(以便在請求使用地圖之前未下載它)。 – user3561092
maps-API會在加載時加載(jsapi必須預先加載) –