max pleaner
max pleaner

Reputation: 26778

js code no longer works when I take it from application.html.erb and put it in its own file

I am loading the Google Maps API in application.html.erb. I also have some JS code which performs the actual communication with the Google Maps API. When I included this code in a script tag in application.html.erb, it worked fine and I saw the map I requested. However, when I moved it into apicombiner.js.coffee, I got an error in the browser telling me error: reserved word "function" in function initialize() {...... apicombiner.js.coffee should automatically compile to application.js when any page in the apicombiner controller is loaded, and this particular page is the 'index' view in apicombiner_controller.

I tried translating the js to coffeescript and reloading the page. I no longer received an error, but the map did not appear. I just got a white page. I also tried renaming the file extension from .js.cofee to only .js. The result was no error, but a white page.

Here is the javascript code:

  function initialize() {
    var mapOptions = {
      center: new google.maps.LatLng(-34.397, 150.644),
      zoom: 8
    };
    var map = new google.maps.Map(document.getElementById("map-canvas"),
        mapOptions);
  }

  google.maps.event.addDomListener(window, 'load', initialize);

Here is the coffeescript version, translated by Js2coffee.org:

initialize = ->
  mapOptions =
    center: new google.maps.LatLng(-34.397, 150.644)
    zoom: 8

  map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions)
  return
google.maps.event.addDomListener window, "load", initialize

By the way the view code is simply <div id="map-canvas" style="width: 100%; height: 100%"></div>

Upvotes: 0

Views: 49

Answers (1)

hunterboerner
hunterboerner

Reputation: 1274

Make sure the JS code is loading in the right order. Sometimes if you have jquery (as an example) defined before your own thing then it can break. Make sure it is in the same order as it was inline.

Upvotes: 1

Related Questions