谷歌地图:使用coffeescript异步加载

时间:2014-03-03 17:26:34

标签: javascript google-maps asynchronous coffeescript

我正在尝试使用coffeescript来模拟这个asynchronously-loaded map

这是我的咖啡因:

initialize = ->
  mapOptions =
    zoom: 8
    center: new google.maps.LatLng(-34.397, 150.644)

  map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions)
  return

loadScript = ->
  script = document.createElement("script")
  script.type = "text/javascript"
  script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&" + "callback=initialize"
  document.body.appendChild script
  return


$(window).load ->

loadScript() 

编译为:

(function() {
var initialize, loadScript;

initialize = function() {
  var map, mapOptions;
  mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644)
  };
  map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
};

loadScript = function() {
  var script;
  script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&" + "callback=initialize";
  document.body.appendChild(script);
};

$(window).load(function() {
  return loadScript();
});

}).call(this);

然后我收到错误:

Uncaught TypeError: Object [object global] has no method 'initialize'

据我所知,我可能需要使initialize()方法可以访问文档的范围,但由于coffeescript将所有模块包装在匿名函数中,因此使这项工作的最佳方法是什么?

1 个答案:

答案 0 :(得分:6)

window.initialize = ->
  # ...

P.S。考虑给它一个更独特的名字。