BackboneJs:从嵌套对象在集合中创建多个模型

时间:2013-05-22 06:02:44

标签: javascript backbone.js backbone-collections backbone-model

{
    "code":"OK",
    "message":"Success",
    "errorFlag":"N",
    "errors":null,
    "data": {
        "images": {
            0: img0,
            1: img1,
            2: img2
        }
    }
}

这是一个REST响应,我想将“图像”记录放在我的集合中,并将每个单独的记录视为模型。

var Image.Model = Backbone.Model.extend({});
var Image.Collection = Backbone.Collection.extend({
    model: Image.Model,
    url: 'rest/url'
});
var images = new Image.TestCollection();
images.fetch();

如何让“images”中的记录成为图像集的唯一模型,并将代码,消息,错误等键放到另一个模型或集合中?

谢谢。

1 个答案:

答案 0 :(得分:2)

使用http://backbonejs.org/#Collection-parse

// server.js
app.get('/api/data', function (req, res) {
    var result = {
        "code": "OK",
        "message": "Success",
        "errorFlag": "N",
        "errors": null,
        "data": {
            "images": {
                0: "img0",
                1: "img1",
                2: "img2"
            }
        }
    };
    res.json(result);
});

// client.js
var Image = Image || {};
Image.Model = Backbone.Model.extend({
});

Image.TestCollection = Backbone.Collection.extend({
    model: Image.Model,
    url: '/api/data',
    parse: function(response) {
        window.response =response;
        var images= [];
        for(var key in response.data.images){
            if(response.data.images.hasOwnProperty(key)){
                images.push(response.data.images[key]);
            }
        }
        return images;
    }
});
var images = new Image.TestCollection();
images.fetch();

P.S。将数据存储在密钥中通常是个坏主意。