json - 如何将 JSON+Patch 与 BackboneJS 嵌套模型/集合一起使用?

标签 json backbone.js nested patch

我的数据模型类似于以下 JSON 结构(只是示例):

var post = {
  id: 123,
  title: 'Sterling Archer',    
  comments: [
    {text: 'Comment text', tags: ['tag1', 'tag2', 'tag3']},
    {text: 'Comment test', tags: ['tag2', 'tag5']}
  ]  
};
在 Backbone 侧,它表示为如下所示的嵌套模型:
var PostModel = Backbone.Model.extend({
   parse: function (response) {
       if (response.comments) {
          response.comments = new Backbone.Collection(response.comments);
       }
       return response;
   }
});

var post = new PostModel(post, {parse: true});
我要申请 rfc6902 (JSONPatch) specification到我的结构。但这里的问题是我的结构不是纯 JSON,而是嵌套的模型/集合单元。
我需要关于如何像官方文档中那样修补嵌套的backbonejs 结构的最佳实践examples :
有人有在 BackboneJS 应用程序中使用 JSON+Patch 规范的经验吗?请与我们分享。
谢谢。
编辑:这是一个简短的例子。假设我需要对我的帖子模型进行一些修改,例如添加评论:
var op = [
  { "op": "add", "path": "/comments/2", "value":  {text: 'Comment test3', tags: ['tag4']}" }
] 
我怎么能用 Backbone 做到这一点:
post.appyPatch(op);
是否有任何最佳实践或/和 Backbone 扩展来做到这一点?

最佳答案

我在 Plunker 中创建了一个工作应用程序使用共享代码和 json-patch.js用于应用补丁的库。我已延长 PostModelapplyPatch应用补丁的方法。这是applyPatch方法代码:

var PostModel = Backbone.Model.extend({
    ...    
    applyPatch: function(op) {
        var postStringify = JSON.stringify(this); // JSON string
        var postAttributesJSON = JSON.parse(postStringify); // JSON object. This is same as postAttributes
        var postPatched = jsonpatch.apply_patch(postAttributesJSON, op); // Patch applied
        var changed = this.changedAttributes(postPatched); // Changed attributes
        var self = this; 
        _.each(_.keys(changed), function(key) {
            if(key == 'comments') {
                self.get('comments').set(changed[key], {merge: true});
            }
        }); 
    }
});

关于json - 如何将 JSON+Patch 与 BackboneJS 嵌套模型/集合一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24879049/

相关文章:

python - 保持嵌套字典中的输入顺序

javascript - 在 for 循环中访问 javascript 对象会返回未定义

python - 如何使用 Python 按值搜索嵌套的 JSON

Javascript:JSON.parse() 阻止自动类型转换

java - 如何使用 REST Api,然后将热门故事显示为 JSON

javascript - 选择正确的 UI 模板工具 -dust.js?

java-POST 方法 415 错误

javascript - 在 JavaScript 中从 JSON 对象创建表

javascript - 数组数据仅每隔两个事件呈现到 HTML 表,否则未定义

backbone.js - 主干事件不起作用