0

仍然在 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(我可以看到它成功地找到了文件,因为我在使用 Chome 检查器的网络请求中将其视为 200):

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

提前致谢!

更新:

修复了无效的 json,但仍然看到一个空的 ToiletryItems 集合。有任何想法吗?

4

1 回答 1

0

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

parse: function(response) { // parse is not being called, not sure why?
    this.set(response[0].name, 'name');
    return response[0].items;
},
于 2013-03-04T09:39:52.740 回答