Backbone.js 集合集合 [英] Backbone.js Collection of Collections
问题描述
我想弄清楚如何使用backbone.js 制作集合的集合.我对骨干很陌生.我有类似以下情况:
I'm trying to figure out how to make a Collection of collections with backbone.js. I'm pretty new to backbone. I have something like the following situation:
+---------------+ +------------------+
| Playlists | | Playlist |
|---------------| 0..* |------------------|
| +-------------->| Name |
| | | |
| | | |
+---------------+ +-------+----------+
|
|
|0..*
v
+------------------+
| Track |
|------------------|
| Name |
| Artist |
| |
+------------------+
在代码中,这看起来类似于:
In code this looks similar to this:
var trackModel = Backbone.Model.extend({
//trackdata
});
var playlistModel = Backbone.Collection.extend({
model : trackModel,
url : "playlist"
});
var playlistsModel = Backbone.Collection.extend({
url : "playlists",
model : playlistModel //This pretty sure doesn't work like I want, because there is no model attribute for collections :S
});
但是我总是在 js 控制台中收到一个错误说:
However I always receive an error in the js console saying:
Uncaught TypeError: Object [object Object] has no method '_validate'
当我尝试执行触发验证的函数时(如添加、获取、...)
when I try to execute a function that triggers the validate (like add, fetch, ...)
如果我将 validate
或 _validate
函数添加到任何集合或模型中,这没有区别.
It makes no difference if i add the validate
or _validate
function to any of the collections or models.
我相信这是因为backbone.js 不支持集合中的集合.还有其他有效的方法吗?
I believe this is because backbone.js doesn't support collections in collections. Is there another way that works?
更新:
这是现在的样子
var Track = Backbone.Model.extend({
//trackdata
});
var Tracks = Backbone.Collection.extend({
model:Track;
});
var Playlist = Backbone.Model.extend({
//name : ...
tracks: new Tracks ()
});
var Playlists = Backbone.Collection.extend({
url : "playlists",
model : Playlist
});
推荐答案
您可以通过将 Playlist
从集合转换为模型来解决您的问题.如果您考虑一下,Playlist
可能还有其他属性(例如名称),这些属性在集合上是不可设置的.
You'd solve your problem by turning your Playlist
from a collection into a model. If you think about it, a Playlist
would probably have other attributes anyway (e.g. name) that wouldn't be settable on a collection.
Playlists
那么将是 Playlist
模型(而不是集合)的集合,它应该可以正常工作.
Playlists
would then be a collection of Playlist
models (instead of collections), which should work without error.
var Track = Backbone.Model.extend({
//trackdata
});
var Playlist = Backbone.Model.extend({
model : Track
});
var Playlists = Backbone.Collection.extend({
url : "playlists",
model : Playlist
});
这篇关于Backbone.js 集合集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!