0

我正在尝试将数据从 json 文件解析为集合视图,该文件中的每组数据都有数字键。JSON 看起来像这样:

{
    "0": {
        "artifact_id": "36",
        "timestamp": "2013-08-20 11:59:00",
        "modified": "2013-08-20 11:59:00",
        "text": "Why did the last one duplicate? I don't think I clicked it twice...",
        "author_desc": "",
        "object_type": "artifact",
        "comments": []
    },
    "1": {
        "artifact_id": "35",
        "timestamp": "2013-08-20 11:57:51",
        "modified": "2013-08-20 11:57:51",
        "text": "This is a new artifact for a new day.",
        "author_desc": "",
        "object_type": "artifact",
        "comments": []
    },
    "2": {
        "artifact_id": "34",
        "timestamp": "2013-08-20 11:57:50",
        "modified": "2013-08-20 11:57:50",
        "text": "This is a new artifact for a new day.",
        "author_desc": "",
        "object_type": "artifact",
        "comments": []
    }
}

如何编写模型解析以将每个条目(0、1、2 ...等)作为数据中的每个模型?

这是我的收藏,下面是 Casey 的建议添加,但它似乎没有运行 parse 方法:

var FriendCollection = Backbone.Collection.extend({
    model: FriendModel,
    parse: function(data) {
        console.log('running parse');
        return _.map(data, _.identity);
    }
});
var friendCollection = new FriendCollection();
friendCollection.reset(friendjson);
4

2 回答 2

2

Collection#reset不打电话parse,也没有办法让它打电话parse。你有几个选择:

  1. 手动转换friendjson为数组并给出reset该数组。
  2. 完全不要reset,只需friendjson交给集合的构造函数并包含{parse: true}option
  3. 如果您包含一个选项reset,请用您自己的版本替换您的收藏。parse{parse: true}

1应该很明显。

2看起来像这样:

var friendCollection = new FriendCollection(friendjson, { parse: true });

演示:http: //jsfiddle.net/ambiguous/dbM82/

3看起来像这样:

var FriendCollection = Backbone.Collection.extend({
    //...
    reset: function(models, options) {
        if(options && options.parse) {
            delete options.parse;
            models = this.parse(models);
        }
        return Backbone.Collection.prototype.reset.call(this, models, options);
    }
});

var friendCollection = new FriendCollection();
friendCollection.reset(friendjson, { parse: true });

演示:http: //jsfiddle.net/ambiguous/Rs8es/

于 2013-08-25T17:55:57.127 回答
0

使用Collection#parse方法。

var MyCollection = Backbone.Collection.extend({
  parse: function (data) {
    return _.map(data, _.identity);
  }
});
于 2013-08-25T17:19:15.683 回答