Sim*_*ken 17 nested-attributes backbone.js
我的许多Backbone模型经常处理嵌套模型和集合,到目前为止我正在使用组合defaults
,parse
并toJSON
手动实现嵌套:
ACME.Supplier = Backbone.Model.extend({
defaults: function() {
return {
contacts: new ACME.Contacts(),
tags: new ACME.Tags(),
attachments: new ACME.Attachments()
};
},
parse: function(res) {
if (res.contacts) res.contacts = new ACME.Contacts(res.contacts);
if (res.tags) res.tags = new ACME.Tags(res.tags);
if (res.attachments) res.attachments = new ACME.Attachments(res.attachments);
return res;
}
});
ACME.Tag = Backbone.Model.extend({
toJSON: function() {
return _.pick(this.attributes, 'id', 'name', 'type');
}
});
Run Code Online (Sandbox Code Playgroud)
我看了几个插件,基本上和上面一样,但是控制和更多的样板很少,所以我想知道是否有人对这个常见的Backbone.js问题有更优雅的解决方案.
编辑:我最终采用以下方法:
ACME.Supplier = Backbone.Model.extend({
initialize: function(options) {
this.tags = new ACME.Tags(options.tags);
},
parse: function(res) {
res.tags && this.tags.reset(res.tags);
return res;
}
});
ACME.Tag = Backbone.Model.extend({
toJSON: function() {
return _.pick(this.attributes, 'id', 'name', 'type');
}
});
Run Code Online (Sandbox Code Playgroud)
值得注意的是,后来我发现您需要通过对象将嵌套的模型/集合数据从构造函数传递到嵌套模型的构造函数中options
.
我认为您的方法没有任何问题.
恕我直言的Model.parse()
方法,如果为此:在特殊的解析行为需要时被覆盖.
我唯一想改变的就是这样的事情:
if (res.tags) res.tags = new ACME.Tags(res.tags);
Run Code Online (Sandbox Code Playgroud)
为了这:
if (res.tags) this.tags.reset(res.tags);
Run Code Online (Sandbox Code Playgroud)
由于你已经有了一个ACME.Tags
集合实例,我会重用它.
我也不喜欢defaults
实现,我习惯于在初始化中使用,Model.initialize()
但我认为这是一个品味问题.