所以我正在创建一个" GoogleMap组件"在单页应用程序中。
我得到了一些受AS2专家启发的模式。他希望SPA可以使用GoogleMaps。当然,模式的一些目标是封装和可重用性。
模式如下:
GoogleMap = { instances: [] }; //static instance,wrapper class
GoogleMap.get = function () {
var mapCanvas = document.createElement('div');
if (this.instances.length > 0) {
return this.instances.pop();
}
var map = new google.maps.Map(mapCanvas, mapOptions); //mapOptions are defined don't worry
return mapCanvas;
}
GoogleMap.destroy = function (googleMap) {
this.instances.push(googleMap);
}
然后在我的HTML中:
<script type="text/javascript">
function start() {
var mapDiv = GoogleMap.get();
document.body.appendChild(mapDiv);
//here lies my issue
//mapDiv.setMapCenter({ lat: 90, long: 90 });
}
window.onload = start;
</script>
我希望能够将对象添加到mapDiv,它现在只是一个html元素。
我认为Javascript中的所有变量都从Object继承,除了null和undefined。所以我认为我可以做到,GoogleMap.get
:
var mapCanvas = document.createElement('div');
mapCanvas.prototype.setMapCenter = function(lat,long){ //error no prototype!
var location = new google.maps.LatLng(lat,long);
this.instance.setCenter(location);
return mapCanvas, which has a method that the caller can use to set lat and long, awesome! If only it worked the way my mind it thinking it would
}
但var mapCanvas没有原型,只是<div>