Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add json to backbone,js collection using fetch

I am trying to get backbone.js to load json. The json loads but i am not sure how to get the items into my collection. Or maybe that happens automatically and i just can't trace out. scope issue?

//js code

//model
var Client = Backbone.Model.extend({
    defaults: {
        name: 'nike',
        img: "http://www.rcolepeterson.com/cole.jpg"
    },
});
//collection
var ClientCollection = Backbone.Collection.extend({
    defaults: {
        model: Client
    },
    model: Client,
    url: 'json/client.json'
});
//view
var theView = Backbone.View.extend({
    initialize: function () {
        this.collection = new ClientCollection();
        this.collection.bind("reset", this.render, this);
        this.collection.bind("change", this.render, this);
        this.collection.fetch();
    },
    render: function () {
        alert("test" + this.collection.toJSON());
    }
});
var myView = new theView();

//json

{
    "items": [
        {
            "name": "WTBS",
            "img": "no image"
        },

        {
            "name": "XYC",
            "img": "no image"
        }
    ]
}
like image 210
Cole Peterson Avatar asked Dec 22 '11 18:12

Cole Peterson


1 Answers

Your json is not in the correct format, you can fix the json or add a hint to backbone in the parse method:

var ClientCollection = Backbone.Collection.extend({
    defaults: {
        model: Client
    },
    model: Client,
    url: 'json/client.json',

    parse: function(response){
       return response.items;
    }
});

Or fix your JSON:

 [
        {
            "name": "WTBS",
            "img": "no image"
        },

        {
            "name": "XYC",
            "img": "no image"
        }
    ]
like image 71
Esailija Avatar answered Nov 06 '22 12:11

Esailija