Nic*_*ray 4 javascript backbone.js
在骨干中,什么是在作者和书籍之间存储关系(在localstorage中)的理想方式.
是否可以将集合作为属性或使用数组或......?
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")
});
Run Code Online (Sandbox Code Playgroud)
在Backbone中没有一种真正的方法来处理嵌套集合.从Backbone FAQ引用:
Backbone不包括对嵌套模型和集合的直接支持,或者"有很多"关联,因为在客户端有许多用于建模结构化数据的良好模式,Backbone应该为实现它们中的任何一个提供基础.
FAQ还提供了一种模式,并提供了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;
}
});
Run Code Online (Sandbox Code Playgroud)
这些评论有希望解释它是如何工作的,但关键是你可以像平常一样使用模型:用集合,数组或什么都没有初始化子节点,从服务器获取,将它们发送到服务器,它应该全部透明地工作.要编写相当多的样板代码,但如果你发现自己重复相同的代码,那么抽象到基类中相对简单.
编辑:小修正,您不需要books
在defaults
对象中定义,因为构造函数在缺少时创建它.
/ code sample未经测试