Javascript Backbone.js集合';s的取数呼叫出错
我仍在绞尽脑汁,遇到了一个问题,当我从文件中传递JSON时,我的集合将无法填充。fetch()调用出错,但我不确定如何准确地调试它,因为我的console.log()没有告诉我任何有用的东西(就我所知如何通过它们) 代码如下:Javascript Backbone.js集合';s的取数呼叫出错,javascript,backbone.js,backbone-events,javascriptmvc,backbone.js-collections,Javascript,Backbone.js,Backbone Events,Javascriptmvc,Backbone.js Collections,我仍在绞尽脑汁,遇到了一个问题,当我从文件中传递JSON时,我的集合将无法填充。fetch()调用出错,但我不确定如何准确地调试它,因为我的console.log()没有告诉我任何有用的东西(就我所知如何通过它们) 代码如下: ItemGroup = Backbone.Collection.extend({ model: Item, // left out definition since it's very simple url: 'js/items.json',
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(我可以看到它正在成功地找到该文件,因为我使用Chome inspector在网络请求中将其视为200):
提前谢谢
更新:
修复了无效的json,但仍看到空的toiletryItems集合。有什么想法吗?发现问题出在我的解析函数上。响应参数是一个数组,因此该函数应为:
parse: function(response) { // parse is not being called, not sure why?
this.set(response[0].name, 'name');
return response[0].items;
},
parse: function(response) { // parse is not being called, not sure why?
this.set(response[0].name, 'name');
return response[0].items;
},