0

我剛開始使用backbone.js,並且遇到了一些問題。的代碼示例:Backbone.Collection.where錯誤未捕獲TypeError:i.matches不是函數

var Product = Backbone.Model.extend({ 
    defaults: { 
    id: 0, 
    category: 0, 
    material: '', 
    capacity: 0, 
    sharpe: 0 
    }, 
    initialize: function(){ 
    console.log(this.get('id')); 
    }, 
    Show: function() { 
    $(".products__item_" + this.get('id')).show('fast'); 
    } 
}); 

var Products = Backbone.Collection.extend({ 
    model: Product 
}); 

var products = new Products(); 

$(".products__item").each(function(index) { 
    var product = new Product({ 
    id: $(this).data('id'), 
    category: $(this).data('category'), 
    material: $(this).data('material'), 
    capacity: $(this).data('capacity'), 
    sharpe: $(this).data('sharpe') 
    }); 
    products.add(product); 
}); 

var temp = products.where({ id: 3272 }) 

所以,當我嘗試Backbone.Collection運行在那裏我得到Uncaught TypeError: i.matches is not a function錯誤。任何想法我做錯了什麼?

+0

在''.products__item「','show()'方法等(*大部分DOM操作*)上迭代的代碼應該是Backbone.View'的理想部分。如果您可以創建演示片段或小提琴來演示問題,這將會很有幫助。 –

回答

2

看起來不錯,我猜測它是因爲order of operations在加載數據之前運行where()

http://jsfiddle.net/8ru16k5v/

var products = new Backbone.Collection(); 

products.add({ 
    id: 3271, 
    category: 10, 
    material: 'wood', 
    capacity: 10, 
    sharpe: 10 
}); 
products.add({ 
    id: 3272, 
    category: 0, 
    material: 'steal', 
    capacity: 10, 
    sharpe: 40 
}) 

var temp = products.where({ id: 3272 })[0].toJSON() 
console.log(temp) 
alert(JSON.stringify(temp)) 

PS。請不要在模型中做Show()。製作一個Backbone.View,附上你的收藏。並使用events like collection.on('sync', doSomethingImportant)

+0

*「在加載數據之前運行where()的操作順序*」 - 您爲什麼這麼認爲......? 他似乎在循環中添加產品後調用'where()'。 –

相關問題