【发布时间】: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()
【问题讨论】: