【问题标题】:How to use JSON+Patch with BackboneJS nested model/collection?如何将 JSON+Patch 与 BackboneJS 嵌套模型/集合一起使用?
【发布时间】:2014-07-22 04:40:33
【问题描述】:

我的数据模型看起来像下面的 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,而是嵌套的模型/集合单元。

我需要关于如何修补我的嵌套主干js结构的最佳实践,如官方文档examples

有没有人有在您的 BackboneJS 应用程序中使用 JSON+Patch 规范的经验?请与我们分享。

谢谢。

编辑:这里是一个简短的例子。假设我需要对我的帖子模型进行一些修改,例如添加评论:

var op = [
  { "op": "add", "path": "/comments/2", "value":  {text: 'Comment test3', tags: ['tag4']}" }
] 

我怎么能用骨干做到这一点:

post.appyPatch(op);

是否有任何最佳实践或/和骨干扩展?

【问题讨论】:

  • 不清楚你想用 PATCH 完成什么,但在我看来你会想要覆盖模型的 toJSON 方法以将结构转换回有效的 JSON 无论如何。
  • 对不起,我已经更新了帖子
  • 很遗憾,Backbone 中的 async 方法不支持这种类型的请求。你总是可以自己扩展它。那将是best practice恕我直言。您可以随时查看this JSON patch library 并获得一些线索。

标签: json backbone.js nested patch


【解决方案1】:

我使用共享代码和json-patch.js 库在Plunker 中创建了一个工作应用程序,用于应用补丁。我已经用应用补丁的applyPatch 方法扩展了PostModel。这里是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});
            }
        }); 
    }
});

【讨论】:

  • 感谢您的回答。但是我在您的代码中看到以下问题: 1. 在this.set(postPatched) 之后我丢失了 cmets 集合。 2.打补丁后更换整个模型效率不高。我们可以更新嵌套模型的特定单元可能会更好。在我的示例中,它只是将新模型添加到“cmets”集合中,而不是替换一个。你有什么想法吗?
  • 抱歉,我错过了嵌套集合。嵌套集合可能无法具有通用功能。我已经修改了Plunker 中的应用程序。让我知道它是否有帮助。
  • 感谢您的回复,我认为可以在不了解这些名称(例如“cmets”)的情况下为任何嵌套模型制作它。
猜你喜欢
  • 2017-02-28
  • 2012-07-18
  • 2015-10-16
  • 1970-01-01
  • 2017-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-07
相关资源
最近更新 更多