javascript - Backbone Js - 解析数据问题

标签 javascript jquery json backbone.js

我正在尝试将数据从 json 文件解析到 Collection View ,该文件中的每组数据都有数字键。 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 建议添加的内容,但它似乎没有运行解析方法:

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

最佳答案

Collection#reset不打电话parse并且没有办法让它调用parse。您有几个选择:

  1. 手动将 friendjson 转换为数组,并重置该数组。
  2. 根本不重置,只需将friendjson 交给集合的构造函数并包含 {parse: true} option .
  3. 如果您包含 {parse: true} 选项,请将集合的 reset 替换为您自己的调用 parse 的版本。

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/

关于javascript - Backbone Js - 解析数据问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18431571/

相关文章:

javascript - 编写 ECMAScript5 兼容代码

javascript - 如何显示所选商品的附加值?

ajax - jQuery监控AJAX查询创建的表单字段

javascript - Angular $http 正在发送 OPTIONS 而不是 PUT/POST

json - 在 json.Unmarshal 之后接收零初始化对象

jquery - getJson 不返回任何内容

javascript - JQuery——如何实现类似 mac os dock 的显示/隐藏行为的动画?

javascript - 自定义选择框 - 选择选项时占位符中的数据图标未正确更新

php - 弹出一个带有 php var 的 javascript 对话框

javascript - 在 Firefox 中通过 2 次滚动检测滚动到底部