Search code examples
javascriptjsonbackbone.js

Backbone Collection from URL json


[{"uniqueId":61,"content":"test","createTextDate":"time"}]

this is /data/commentList.json

var Comment = Backbone.Model.extend({
    defaults: {
        uniqueId: null,
        createTextDate: null,
        content: null
    }
});

Model for Backbone Collection

var List = Backbone.Collection.extend({
    model: Comment,

    url: function() {
        return '/data/commentList.json';
        },      

        parse: function(response) {
            return response.results;
        },
        sync: function(method, model, options) {
            var that = this;
            var params = _.extend({
                type: 'GET',
                dataType: 'jsonp',
                url: that.url(),
                processData: false
            }, options);

            return $.ajax(params);
        }
});

Backbone Collection

var ListView = Backbone.View.extend({
    el: $('#test'),
    initialize: function() {
        _.bindAll(this, 'render');
        this.collection = new List();
        this.render();
    },
    render: function() {
        var self = this;
        this.collection.fetch({
            success: function() {
                console.log("SUCESS");
                console.log(that.collection.toJSON());
            },
            error: function() {
                console.log('Failed to fetch!');
            }
        });
    }
});

Console log

Failed to fetch!

How to make Backbone Collection using jSON url?


Solution

  •     parse: function(response) {
            return response.results;
        },
    

    Above code assumes your server returns

    {"results": [comment1, comment2]}
    

    You rarely need to override sync method.