2012-11-04 50 views
1

我正在嘗試與backbone,coffescript和google maps api一起工作。我能夠渲染地圖並添加中心標記。我在地圖上添加地點集合作爲漫遊者時遇到問題。如何與視圖中的其他函數或應用程序的其他部分共享下面的@map對象?如何從Backbone/Coffee中的其他視圖函數訪問我的@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!" 
    }) 

回答

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僅僅是下劃線的each和一個瘦包裝fine manual具有這樣說each

每個_.each(list, iterator, [context])別名:forEach

在迭代元素的列表,得到各依次的迭代功能。 迭代器綁定到上下文對象,如果通過。

你不指定場景,當你使用each

@collection.each(@addMarker) 

所以@(AKA this)將window(或任何全球範圍內爲您的環境)中addMarker。你想@成爲您的視圖,這樣或者指定上下文:

@collection.each(@addMarker, @) 

或定義addMarkerbound function

addMarker: (location) => 
    #... 

你也可以使用在您的視圖的initialize方法_.bindAll但很少有CoffeeScript的。

相關問題