在 CoffeeScript 中调用全局函数

call a global function in CoffeeScript

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

# 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 获取脚本 异步 。在 page.included_google_maps_js_api == undefined 为真的情况下,您在调用 initMap 之前不需要等待结果。

你只需要一个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