3
{
    "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();

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

谢谢你。

4

1 回答 1

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

PS 在密钥中存储数据通常是个坏主意。

于 2013-05-22T07:08:10.460 回答