sekmo sekmo - 1 year ago 135
CoffeeScript Question

call a global function in CoffeeScript

I'm getting a strange behavior with CoffeeScript: the

initMap
function is correctly called from the loaded script (
&callback=initMap
), but I have an error triggered by the last line at
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


What I find funny is that this other snippet is working flawlessly:

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

Answer Source

$.getScript gets the script asynchronously. You're not waiting for the result of that before calling initMap in the case where page.included_google_maps_js_api == undefined is true.

You just need an else (since you're using &callback=initMap to call it in the case where need to load):

$(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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download