2015-02-10 97 views
0

我無法從地圖視圖的render()函數中獲取集合中的數據。我試圖以多種方式獲取數據,但我似乎無法正確地獲取數據。這是我目前在https://jsfiddle.net/huntonas/pt17bygm/89/骨幹收集數據谷歌地圖

APP = {}; 
APP.ArtPiece = Backbone.Model.extend({ 
    defaults: { 
     first_name: null, 
     title: null, 
     location: null, 
     description: null, 
     last_name: null, 
     longitude: null, 
     latitude: null, 
     type: null, 
     medium: null 
    } 
}); 
APP.ArtPieces = Backbone.Collection.extend({ 
    model: APP.ArtPiece, 
    url: 'https://data.nashville.gov/resource/dqkw-tj5j.json' 
}); 
APP.artPieces = new APP.ArtPieces(); 

APP.Map = Backbone.Model.extend({ 
    defaults: { 
     center: new google.maps.LatLng(36.159480, -86.792112), 
     zoom: 8, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    } 
}); 
APP.map = new APP.Map(); 

APP.MapView = Backbone.View.extend({ 
    id: 'map', 
    initialize: function() { 
     this.collection.fetch(); 
     this.map = new google.maps.Map(this.el, this.model.attributes); 
     this.render(); 
    }, 
    render: function() { 

     this.collection.each(function (artPiece) { 
      console.log(artPiece.toJSON()); 
      var marker = new google.maps.Marker({ 
       position: new google.maps.LatLng(artPiece.latitude, artPiece.longitude), 
       title: artPiece.title 
      }); 
      return marker; 
     }, this); 
     $('#map').replaceWith(this.el); 
    } 
}); 
APP.mapView = new APP.MapView({ 
    model: APP.map, 
    collection: APP.artPieces 
}); 

,但它沒有顯示在任何的console.log。我認爲這是因爲集合中沒有任何內容,但我不知道該集合的哪個位置調用fetch()。有什麼幫助嗎?謝謝。

回答

2

你的主要問題有兩方面:

  1. Collection#fetch是一個AJAX調用和你沒有任何的關注,當它與您的集合數據返回。
  2. artPiece裏面的this.collection.each回調將是一個模型實例。模型不會將屬性存儲在屬性中,它們存儲在attributes屬性中,並通過model.get('attribute_name')訪問。

修復第一個問題很簡單。呼叫fetchreset: true選項(這樣就會引發'reset'事件),然後綁定您的視圖的render到集合的'reset'事件:

initialize: function() { 
    this.collection.fetch({ reset: true }); 
    this.listenTo(this.collection, 'reset', this.render); 
    //... 
} 

現在你的觀點的render將被調用時,收集從遠程獲取的東西服務器。

解決第二個問題也很簡單,我們將解決另一個問題。當你創建一個標記時,你需要告訴它使用哪個映射,所以你需要將map: this.map添加到構造函數參數中。如果我們做到這一點,並開始使用get,我們有:

el: '#map', 
render: function() { 
    this.collection.each(function (artPiece) { 
     var marker = new google.maps.Marker({ 
      map: this.map, 
      position: new google.maps.LatLng(
       artPiece.get('latitude'), 
       artPiece.get('longitude') 
      ), 
      title: artPiece.get('title') 
     }); 
    }, this); 
} 

有沒有必要說id: 'map'然後調用replaceWithrender,你就可以說el: '#map'代替。

更新演示:https://jsfiddle.net/ambiguous/jj8kopyk/

+0

您的解決方案奏效。感謝您的幫助和解釋。只需在你的小提琴中編輯一些東西,調用google地圖需要是https,而渲染仍然需要'$('#map')。replaceWith(this.el);'顯示創建的地圖,但是我有不正確,你的例子修正了它們。我在[小提琴](https://jsfiddle.net/huntonas/pt17bygm/99/)中有一個工作解決方案。再次感謝你! – user3734990 2015-02-10 15:50:04

+0

如果你在視圖中有'el:'#map''並且刪除'id:'map'',那麼你不需要'replaceWith'。 – 2015-02-10 17:52:06