我在CoffeeScript中遇到一种奇怪的行为:已从加载的脚本(initMap)正确调用&callback=initMap函数,但是在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


我觉得有趣的是,另一个代码段运行正常:

$(document).on 'turbolinks:load', ->
  if $('#restaurant-map').length > 0 && page.included_google_maps_js_api == undefined
    google_maps_api_key = 'xxx'
    $.getScript('https://maps.googleapis.com/maps/api/js?key=' + google_maps_api_key + '&callback=initMap')
    page.included_google_maps_js_api = true
  else if ($('#restaurant-map').length > 0)
    initMap()

最佳答案

$.getScript异步获取脚本。在initMap为true的情况下,在调用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

关于javascript - 在CoffeeScript中调用全局函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47284545/

10-12 21:22