0

Still wrapping my head around Backbone, and running into an issue where my Collection won't populate when I'm passing it JSON from a file. The fetch() call is erroring out, but I'm not sure how to debug it exactly, as my console.log()'s aren't telling me anything useful (as far as I know how to dig through them).

Here's the code:

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 });

And here's my json (I can see that's it's successfully finding the file, since I see it as a 200 in the network requests using the Chome inspector):

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

Thanks in advance!

UPDATE:

Fixed the invalid json, but still seeing an empty toiletryItems collection. Any ideas?

Rohan
  • 383
  • 3
  • 6
  • 14

1 Answers1

0

Discovered the problem was with my parse function. The response param is an array, and so that function should be:

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