Backbone.js Collection'的fetch调用出错

Backbone.js Collection's fetch call is erroring out

本文关键字:fetch 调用 出错 js Collection Backbone      更新时间:2023-09-26

仍然围绕着Backbone,并且遇到了一个问题,当我从文件传递JSON时,我的Collection不会填充。fetch()调用出错了,但我不确定如何准确地调试它,因为我的console.log()没有告诉我任何有用的东西(据我所知如何挖掘它们)。

代码如下:

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在网络请求使用chrome检查器):

[
 {
    'name' : 'toiletries',
    'items' : [
        { 'name': 'toothbrush' },
        { 'name': 'deodorant' },
        { 'name': 'toothpaste' },
    ]
 }
]

提前感谢!

更新:

修复了无效的json,但仍然看到一个空的toiletryItems集合。什么好主意吗?

发现问题与我的解析函数。响应参数是一个数组,因此该函数应该是:

parse: function(response) { // parse is not being called, not sure why?
    this.set(response[0].name, 'name');
    return response[0].items;
},