js.coffee.erb - 同步问题?

时间:2012-11-12 22:49:23

标签: javascript ruby-on-rails-3 google-maps-api-3 coffeescript erb

我正在尝试将数据库中的纬度和经度值插入我的谷歌地图coffeescript。

jQuery ->
  initialize()

initialize = ->
  myOptions =
    center: new google.maps.LatLng(<%= @location.latitude %>, <%= @location.longitude %>)
    zoom: 12
    mapTypeControlOptions: {mapTypeIds: ["OSM", "OCM", "MQ", google.maps.MapTypeId.HYBRID]}
  map = new google.maps.Map $('#map_canvas')[0], myOptions

[...]

我收到以下错误消息:

 undefined method `latitude' for nil:NilClass
   (in /Users/sg/rails-projects/geo_rails_test/app/assets/javascripts/gmap.js.coffee.erb)

建议我的位置对象

@location = Location.find(params[:id])
在解析js.coffee.erb文件时尚未实例化

。 (??)

我已经使用硬编码值测试了coffeescript,@ location.latitude在我看来完美无缺。 任何想法出了什么问题?

1 个答案:

答案 0 :(得分:2)

您的(Java |咖啡)脚本资产将在控制器运行之前处理并发送到浏览器。这意味着@location不会来自您的控制器,它将来自self转换为JavaScript时的.js.coffee.erb。在部署到生产环境时,资产将(甚至应该)在任何事情发生之前进行编译,因此@location没有任何有用的希望。

您应该在控制器的ERB而不是资产中构建数据:

<!-- Somewhere in the appropriate app/views/... file... -->
<script type="text/javascript">
    window.global_location = { lat: <%= @location.latitude %>, lng: <%= @location.longitude %> }; 
</script>

然后您的资产可以通过this_location global:

获取数据
center: new google.maps.LatLng(global_loc.lat, global_loc.lng)

或者您可以尝试通过AJAX调用加载位置。

仅针对每个应用程序常量和配置值在资产中使用ERB,不要尝试在资产中使用ERB来处理在应用程序运行时发生更改的任何内容。