1

バックボーン、コフェスクリプト、Google マップ API を使用しようとしています。マップをレンダリングしてセンター マーカーを追加できます。場所のコレクションをモーカーとしてマップに追加する際に問題が発生しています。以下の @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!"
    })
4

1 に答える 1

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コレクションのメソッドはアンダースコアの単なる薄いラッパーでeachあり、優れたマニュアルには次のように書かれていeachます。

_.each(list, iterator, [context])エイリアス:forEach

要素のリストを反復処理し、それぞれを反復子関数に生成します。イテレータが渡された場合、イテレータはコンテキストオブジェクトにバインドされます。

使用するときにコンテキストを指定していませんeach

@collection.each(@addMarker)

したがって、@(AKA this)はwindow(または環境内のグローバルコンテキストが何であれ)内部になりますaddMarker。あなた@は自分の見解になりたいので、コンテキストを指定します。

@collection.each(@addMarker, @)

またはバインドさaddMarkerれた関数として定義します:

addMarker: (location) =>
  #...

_.bindAllビューのメソッドで使用することもできますinitializeが、CoffeeScriptではまれです。

于 2012-11-04T20:01:12.067 に答える