2012-09-29 27 views
3

您好我有一個集合,它使用fetch()從API進行初始提取。在用戶的交互,第二獲取被觸發,但不是使用原始fetch(),我用了一個fetchNew(),我定義自己:Backbone.js:Uncaught TypeError:Object#<Object> has no method'get'

收集

ListingCollection = Backbone.Collection.extend({ 
    model: Listing, 
    url: '/api/search_by_bounds', 

    fetchNew: function(options) { 
     options = options || {}; 
     var collection = this, 
      success = options.success; 
     options.success = function(resp, status, xhr) { 
      _(collection.parse(resp, xhr)).each(function(item) { 
       // added this conditional block 
       if (!collection.get(item.id)) { 
        // Update collection 
        collection.add(item, {silent:true}); 
        // Render View 
        new ListingMarkerView({ model:item }).render(); 
       } 
      }); 
      if (!options.silent) { 
       collection.trigger('reset', collection, options); 
      } 
      if (success) success(collection, resp); 
     }; 
     return (this.sync || Backbone.sync).call(this, 'read', this, options); 
    } 
}); 

這將僅添加新車型集合,並僅渲染這些新模型的視圖。 (如果所有的意見是刪除和重新渲染,就會造成閃爍)

查看

ListingMarkerView = Backbone.View.extend({ 

    render: function() { 
     var marker = L.marker([this.model.get('lat'), this.model.get('lng')]); 
     markers.addLayer(marker); 
    }, 

    close: function() { 
     this.unbind; 
    } 

}); 

錯誤

但是我得到一個錯誤:

Uncaught TypeError: Object #<Object> has no method 'get' 

這對應於這條線ListingMarkerView

var marker = L.marker([this.model.get('lat'), this.model.get('lng')]); 

調試

如果我是呈現ListingMarkerView

console.log(item) 
new ListingMarkerView({ model:item }).render(); 

前行放置console.log(item)我確實看到一個有效的item

Object 
    id: "2599084" 
    lat: "42.276852" 
    lng: "-71.165421" 
    price: "2850" 
    __proto__: Object 

所以.. 。

問題

什麼似乎是問題?這怎麼解決?謝謝!

+0

我寧願去照常'.reset',你爲什麼要這麼做?你可以發佈一個鏈接到工作現場,以便我可以檢查嗎? –

+0

'.reset'是否會刪除最初的'fetch()'中的項目,但不會在隨後的調用中?我希望只是在不刪除舊的模型的情況下追加新的模型。 – Nyxynyx

+0

如果你想添加新的而不刪除舊的,使用'fetch({add:true})''。但是,你仍然應該明白我給你的問題的答案,因爲它肯定會出現在其他地方。 – blockhead

回答

6

問題是渲染沒有this正確定義。在這樣的視圖類 添加initialize方法:

initialize: function() { 
    _.bindAll(this); //Make all methods in this class have `this` bound to this class 
} 
+0

我加了'_.bindAll(this,'render','close');'但是得到了同樣的錯誤 – Nyxynyx

+0

什麼是'this.model'等於? – blockhead

+0

現在很好用!使用'add:true'並更改渲染以觸發'add'而不是'reset',這聽起來很奇怪 – Nyxynyx

相關問題