【问题标题】:call a global function in CoffeeScript在 CoffeeScript 中调用全局函数
【发布时间】:2017-11-14 19:27:54
【问题描述】:

我在使用 CoffeeScript 时遇到了一个奇怪的行为:从加载的脚本 (&callback=initMap) 正确调用了 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

我觉得有趣的是,另一个 sn-p 工作得非常完美:

$(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()

【问题讨论】:

    标签: javascript coffeescript


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-17
      • 2014-03-22
      • 1970-01-01
      • 2012-06-13
      • 1970-01-01
      • 2011-12-10
      相关资源
      最近更新 更多