如何从Backbone / Coffee中的另一个视图函数访问我的@map对象?

时间:2012-11-04 18:56:31

标签: javascript backbone.js coffeescript

我正在尝试使用backbone,coffescript和google maps api。我能够渲染地图并添加中心标记。我在地图上添加一组位置作为morker时遇到问题。如何与视图或应用程序的其他部分中的其他函数共享下面的@map对象?

在addMarker @map中未定义。

render: ->
    $(@el).html(@template())
    primary = @collection.at(@collection.length - 1)
    if primary
      latlng = {}
      @collection.each(@appendLocation)
      latlng['latitude'] = primary.attributes.latitude;
      latlng['longitude'] = primary.attributes.longitude;
      @renderMap(latlng)
   this

  renderMap: (latlng) ->
    view = new Bone.Views.Map()
    $('#map').append(view.render().el)
    latlng = new google.maps.LatLng(latlng['latitude'], latlng['longitude'])
     myOptions =
      zoom: 12
      center: latlng
      mapTypeId: google.maps.MapTypeId.ROADMAP
     @map = new google.maps.Map(view.render().el, myOptions)
    marker = new google.maps.Marker({
      position: latlng,
      animation: google.maps.Animation.DROP,
      map: @map,
      title:"Hello World!"
    })
    @collection.each(@addMarker)

  addMarker: (location)->
    console.log(@map) <-----UNDEFINED
    latlng = new google.maps.LatLng(location.attributes.latitude, location.attributes.longitude)
    console.log location.attributes.latitude
    location_marker = new google.maps.Marker({
      position: latlng,
      animation: google.maps.Animation.DROP,
      map: @map,
      title:"Hello World!"
    })

1 个答案:

答案 0 :(得分:0)

我会假设你的缩进问题只是一个复制/粘贴错误,你的代码看起来真的是这样:

renderMap: (latlng) ->
  view = new Bone.Views.Map()
  $('#map').append(view.render().el)
  latlng = new google.maps.LatLng(latlng['latitude'], latlng['longitude'])
  myOptions =
    zoom: 12
    center: latlng
    mapTypeId: google.maps.MapTypeId.ROADMAP
  @map = new google.maps.Map(view.render().el, myOptions)
  marker = new google.maps.Marker({
    position: latlng,
    animation: google.maps.Animation.DROP,
    map: @map,
    title:"Hello World!"
  })
  @collection.each(@addMarker)

each method on a collection只是Underscore的each的薄包装,而fine manual可以说each

  

每个 _.each(list, iterator, [context])别名:forEach

     

迭代列表元素,依次产生迭代器函数。 迭代器绑定到上下文对象(如果有)。

使用each时,您没有指定上下文:

@collection.each(@addMarker)

所以@(AKA this)将windowaddMarker(或您环境中的全局上下文)@。您希望@collection.each(@addMarker, @) 成为您的视图,因此请指定上下文:

addMarker

或将addMarker: (location) => #... 定义为bound function

initialize

您也可以在视图的{{1}}方法中使用_.bindAll,但这在CoffeeScript中很少见。

相关问题