Mat*_*hew 13 javascript orm model relationship backbone.js
我正在使用backbone.js
例如,假设我们有一个"产品"模型和一个具有多对多关系的"类别"模型.在我的一个观点中,假设我需要检索所有类别的列表,并知道每个类别是否与当前产品模型相关.
我是否设置了"类别"集合并将其作为我的模型的属性,并以某种方式让它访问模型的ID,以便在获取时,它只获取相关的类别?然后我可以获取所有类别并交叉检查它们以查看哪些类别相关,同时还有那些不相关的类别?
我不知道最好的办法是什么.我习惯使用ORM,这在服务器端很容易.
有一个简单的,可定制的解决方案,虽然它可能不那么健壮backbone-relational.
Backbone.ModelWithRelationship = Backbone.Model.extend({
mappings: {},
set: function(attributes, options) {
_.each(this.mappings, function(constructor, key) {
var RelationshipClass = stringToFunction(constructor);
var model = new RelationshipClass();
/* New relational model */
if (!this.attributes[key]) {
this.attributes[key] = (model instanceof Backbone.Collection) ? model : null;
}
/* Update relational model */
if (attributes[key] && !(attributes[key] instanceof Backbone.Model || attributes[key] instanceof Backbone.Collection)) {
if (model instanceof Backbone.Model) {
this.attributes[key] = model;
this.attributes[key].set(attributes[key], options);
} else if (model instanceof Backbone.Collection) {
this.attributes[key].reset(attributes[key], options);
}
delete attributes[key];
}
}, this);
return Backbone.Model.prototype.set.call(this, attributes, options);
}
});
Run Code Online (Sandbox Code Playgroud)
您可以通过创建子类来声明映射Backbone.ModelWithRelationship.
Models.Post = Backbone.ModelWithRelationship.extend({
mappings: {
'comments': 'Collection.CommentCollection',
'user': 'Models.User'
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9362 次 |
| 最近记录: |