2013-08-25 32 views
2

我真的有兩個部分的問題。「this.collection.each不是函數」。它不應該簡單地說「每個」嗎?

控制檯告訴我:「類型錯誤:this.collection.each是不是一個函數」

在短期內我很想知道爲什麼我的代碼不能正常工作。

從長遠來看,我更感興趣知道爲什麼它不告訴我「每個」不是一個函數,因爲這是我試圖調用的方法。

P.S.我已經確認JQuery加載正確,在加載代碼之前,這不是問題。

相關的JavaScript是:

$(function(){ 

var items = [ 
     { name: 'Abe Lincoln', details: 'Is he that guy from that new reality show?'}, 
     { name: 'Captain Planet', details: 'He is our hero'}, 
     { name: 'Karthus', details: 'Press R'}, 
     { name: 'Your Mom', details: 'She misses me'}, 
     { name: 'Teddy Roosevelt', details: 'Makes the most interesting man in the world look boring'} 
    ]; 

    var itemsCollectionView = new ListView({collection: items}); 
    Backbone.history.start(); 
}); 

var ListView = Backbone.View.extend({ 

    el: '#the-list', 

    initialize: function(){ 
     this.render(); 
    }, 

    render: function(){ 
      this.collection.each(function(model){ 
      this.addOne(model); 
     }, this); 
    }, 

    //create an itemview for a model, and add it to the list view 
    addOne:function(model){ 
     var itemView = new ItemView({model: model}); 
     this.$el.append(itemView.render().el); 
    } 
}); 
+0

它是有幫助路徑」。有什麼問題? (另外,試試'forEach'。) – Ryan

+0

謝謝,forEach作品。我將不得不做一些研究來了解爲什麼這會起作用,但不是每個都有效。也許我正在使用的JQuery版本?此外,感謝您填寫我爲什麼控制檯以這種方式工作。不知道是不是因爲這是我做錯了,讓瀏覽器將整個事情解釋爲一種方法,或者只是爲了幫助我找到我的問題。 – user1937279

回答

5

this.collection.each是罰款與骨幹使用,問題是,你是不是通過實際的骨幹集合ItemView控件的實例,但只是一個數組。你需要像下面這樣:

var itemsCollection = new ItemsCollection(items), // substitute your collection variable 
    itemsCollectionView = new ListView({ collection: itemsCollection }); 

而且,我試着骨幹1.0.0和jQuery 1.10.1運行你的代碼,我告訴你整個「獲得

TypeError: Object [object Array] has no method 'each' 
+1

無論出於什麼原因切換到forEach都能夠解決特定的錯誤。這讓我發現了你所預見的問題。感謝您的搶先幫助。這對解決我的下一個問題很有幫助。 – user1937279

+0

如果您發現我的答案合適,您能接受答案嗎?謝謝! –

+1

@ user1937279:數組有一個['forEach'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)方法。 –

相關問題