在CoffeeScript中调用全局函数

时间:2017-11-14 11:24:56

标签: javascript coffeescript

我在CoffeeScript中遇到了一个奇怪的行为:从加载的脚本(initMap)中正确调用了&callback=initMap函数,但我在{{1}的最后一行触发了错误}

initMap()

我觉得有趣的是,这个其他代码片段正在完美运行:

# Declare a global function
@initMap = ->
  restaurantLocation =
    lat: $('#restaurant-map').data("lat")
    lng: $('#restaurant-map').data("lng")
  map = new (google.maps.Map) $('#restaurant-map')[0],
    zoom: 19,
    center: restaurantLocation
  marker = new (google.maps.Marker)
    position: restaurantLocation
    map: map

$(document).on 'turbolinks:load', ->
  if $('#restaurant-map').length > 0
    if page.included_google_maps_js_api == undefined
      google_maps_api_key = 'xxx'
      # correctly called from here...
      $.getScript('https://maps.googleapis.com/maps/api/js?key=' + google_maps_api_key + '&callback=initMap')
      page.included_google_maps_js_api = true
    initMap() # Uncaught ReferenceError: google is not defined

1 个答案:

答案 0 :(得分:1)

$.getScript获取脚本异步。在initMap为真的情况下,您在调用page.included_google_maps_js_api == undefined之前不会等待结果。

您只需要一个else(因为您需要&callback=initMap在需要加载的情况下调用它):

$(document).on 'turbolinks:load', ->
  if $('#restaurant-map').length > 0
    if page.included_google_maps_js_api == undefined
      google_maps_api_key = 'xxx'
      # correctly called from here...
      $.getScript('https://maps.googleapis.com/maps/api/js?key=' + google_maps_api_key + '&callback=initMap')
      page.included_google_maps_js_api = true
    else                  # <== Note the else
      initMap()           #     so we only do this if it's loaded