在主干中,存储作者和书籍之间关系(在本地存储中)的理想方式是什么。
是否可以将集合作为属性,或者应该使用数组还是...?
var book = Backbone.Model.extend({
defaults:{
title: ''
}
});
var books = Backbone.Collection.extend({
model: book
});
var author = Backbone.Model.extend({
defaults:{
firstName: '',
lastName: '',
books: new books()
}
});
var authors = Backbone.Collection.extend({
model: author,
localStorage: new Backbone.LocalStorage("authors")
});
最佳答案
在 Backbone 中处理嵌套集合没有唯一正确的方法。引自 Backbone FAQ :
Backbone doesn't include direct support for nested models and collections or "has many" associations because there are a number of good patterns for modeling structured data on the client side, and Backbone should provide the foundation for implementing any of them.
常见问题解答还建议了一种模式并提供了指向 Extensions, Plugins, Resources 的链接页面,它链接到许多可用于处理嵌套模型和模型关系的库。
也就是说,我有时会这样处理这个问题:
var Author = Backbone.Model.extend({
initialize: function(attrs, options) {
//convert the child array into a collection, even if parse was not called
var books = attrs ? attrs.books : [];
if(!(books instanceof Books)) {
this.set('books', new Books(books), {silent:true});
}
},
//the books property does not need to be declared in the defaults
//because the initialize method will create it if not passed
defaults: {
firstName: '',
lastName: ''
},
//override parse so server-sent JSON is automatically
//parsed from books array to Books collection
parse: function(attrs) {
attrs.books = new Books(attrs.books);
return attrs;
},
//override toJSON so the Books collection is automatically
//converted to an array
toJSON: function() {
var json = Backbone.Model.prototype.toJSON.call(this);
if(json.books instanceof Books) {
json.books = json.books.toJSON();
}
return json;
}
});
评论有望解释它是如何工作的,但重点是您可以像往常一样使用该模型:使用集合、数组或什么都不初始化子项,从服务器获取,将它们发送到服务器,它应该透明地工作。有相当多的样板代码需要编写,但如果您发现自己在重复相同的代码,那么将其抽象为基类相对简单。
编辑 小更正,您不需要 defaults
对象中定义的 books
,因为如果缺少,构造函数会创建它。
/代码示例未测试
关于javascript - Backbone 的一个属性可以包含一个集合吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14315302/