0
仍然围绕着Backbone缠绕我的脑袋,并且遇到了一个问题,即当我从文件传递JSON时,我的集合不会填充。 fetch()调用正在出错,但我不确定如何正确调试它,因为我的console.log()没有告诉我任何有用的信息(据我所知如何挖掘它们)。Backbone.js Collection的抓取调用错误
下面的代码:
ItemGroup = Backbone.Collection.extend({
model: Item, // left out definition since it's very simple
url: 'js/items.json',
initialize: function(models, options) {
this._meta = {};
},
parse: function(response) { // parse is not being called, not sure why?
this.set(response.name, 'name');
return response.items;
},
set: function(val, prop) {
this._meta[prop] = val;
},
get: function(prop) {
return this._meta[prop];
}
});
ItemGroupView = Backbone.View.extend({
el: '#item-container',
initialize: function(options) {
this.collection.bind('reset', this.render, this);
this.collection.fetch({
success : function() {
alert('successful');
},
error : function(collection, xhr, options) { // This is being triggered, not sure why?
console.log(collection);
console.log(xhr);
console.log(options);
}
});
},
processItem: function(item) {
var itemView = new ItemView({ model: item });
this.$el.append(itemView.render().el);
},
render: function() {
console.log(this.collection); // this shows an empty collection
var itemGroupHtml = this.template({ name: this.collection.get('name') });
$(this.main).html(itemGroupHtml);
_.each(this.collection.models, this.processItem, this);
return this;
}
});
var toiletryItems = new ItemGroup();
var toiletryGroupView = new ItemGroupView({ collection: toiletryItems });
这是我的JSON(我可以看到这就是它成功地找到想要的文件,因为我认为这是在使用丁目检查网络请求200):
[
{
'name' : 'toiletries',
'items' : [
{ 'name': 'toothbrush' },
{ 'name': 'deodorant' },
{ 'name': 'toothpaste' },
]
}
]
在此先感谢!
UPDATE:
修正了无效的JSON,但仍显示空toiletryItems集合。有任何想法吗?