簡體   English   中英

將.js轉換為.js.coffee時出現未捕獲的ReferenceError

[英]Uncaught ReferenceError when converting .js to .js.coffee

在將我的.js轉換為.js.coffee沒有更改流或其自身代碼中的任何內容后,我得到了針對以下代碼的map Uncaught ReferenceError

使用.js ,我的腳本運行正常,而.js.coffee不再.js.coffee

我正在使用GMAP API以及時髦的信息窗口,rails 5,ruby 2.4。

你知道為什么嗎?

編輯

為了清楚起見,我沒有在其中mapOptions變量,它只是在我的存儲GMAP Snazzy主題的文件中定義的變量。

markersData = '<%= raw @places_markers.to_json %>'

  markers = []

  icon =
    path: 'M4.415,8.829c2.432,0,4.415-1.983,4.415-4.415 C8.829,1.983,6.846,0,4.415,0S0,1.983,0,4.415C0,6.846,1.983,8.829,4.415,8.829z'
    fillColor: '#2962FF'
    fillOpacity: 1
    anchor: new (google.maps.Point)(0, 0)
    strokeWeight: 1
    scale: 2

  initializeMap = ->
    map = new (google.maps.Map)(document.getElementById('places-map'), mapOptions)

    google.maps.event.addListener map, 'click', ->
      infoWindow.close()

    displayMarkers(markersData)


  createMarker = (latlng, markerInfowindow, icon) ->
    marker = new (google.maps.Marker)(
      map: map
      position: latlng
      icon: icon
      draggable: true)

    markers.push(marker)

    google.maps.event.addListener marker, 'click', ->
      iwContent = markerInfowindow

      infoWindow = new SnazzyInfoWindow(
        marker: marker
        content: iwContent
        placement: 'top'
        maxWidth: 400
        maxHeight: 200
      )

      infoWindow.open(map, marker)

  displayMarkers = (markersData) ->
    bounds = new (google.maps.LatLngBounds)
    places_coordinates = []

    i = 0
    while i < markersData.length
      latlng = new (google.maps.LatLng)(markersData[i].place_lat, markersData[i].place_lng)

      markerInfowindow = markersData[i].infowindow

      places_coordinates.push(latlng)

      createMarker(latlng, markerInfowindow, icon)

      bounds.extend(latlng)
      i++

    markerCluster = new MarkerClusterer(map, markers)
    map.fitBounds(bounds)

  newLocation = (newLat, newLng) ->
    map.setCenter
      lat: newLat
      lng: newLng
    map.setZoom 15

  initializeMap()

mapinitializeMap內的局部變量:

initializeMap = ->
    map = new (google.maps.Map)(document.getElementById('places-map'), mapOptions)
    ...

因此除非您強制將其設置為全局,否則在其他任何地方都不可見。 CoffeeScript中的所有變量都是本地變量,除非您另外明確聲明。

您可以創建一個類,並將map為實例變量:

class YourMap
  constructor:
    @map = new google.maps.Map(...)

  # The rest of your code converted to methods goes here

或者,由於CoffeeScript將代碼包裝在一個自執行函數中以維護其范圍規則,因此您可以在函數外部聲明map

map = undefined
markersData = '<%= raw @places_markers.to_json %>'
markers = []
#...

然后別管其他一切。

在CoffeeScript中,使用類可能被認為更慣用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM