代码之家  ›  专栏  ›  技术社区  ›  sekmo

在CoffeeScript中调用全局函数

  •  0
  • sekmo  · 技术社区  · 7 年前

    我在喝咖啡时有一种奇怪的行为 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()
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   T.J. Crowder    7 年前

    $.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