在 CoffeeScript 中调用全局函数

塞克莫

我在使用 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()
TJ克劳德

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章