我的数据模型类似于以下 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用于应用补丁的库。我已延长 PostModel
与 applyPatch
应用补丁的方法。这是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/