簡體   English   中英

URL json的骨干集合

[英]Backbone Collection from URL json

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

這是/data/commentList.json

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

骨干收集模型

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

骨干收集

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

控制台日志

Failed to fetch!

如何使用jSON網址制作Backbone Collection?

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

上面的代碼假定您的服務器返回

{"results": [comment1, comment2]}

您很少需要重寫sync方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM