javascript Backbone.js 集合集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10388199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Backbone.js Collection of Collections
提问by krial
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:
我想弄清楚如何使用backbone.js 制作集合的集合。我对骨干很陌生。我有类似以下情况:
+---------------+ +------------------+
| 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
});
However I always receive an error in the js console saying:
但是我总是在 js 控制台中收到一个错误说:
Uncaught TypeError: Object [object Object] has no method '_validate'
when I try to execute a function that triggers the validate (like add, fetch, ...)
当我尝试执行触发验证的函数时(如添加、获取、...)
It makes no difference if i add the validate
or _validate
function to any of the collections or models.
如果我将validate
or_validate
函数添加到任何集合或模型中,这没有区别。
I believe this is because backbone.js doesn't support collections in collections. Is there another way that works?
我相信这是因为backbone.js 不支持集合中的集合。还有另一种有效的方法吗?
UPDATE:
更新:
This is how it looks right now
这就是它现在的样子
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
});
采纳答案by Rob Hruska
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.
您可以通过将您Playlist
的收藏品变成模型来解决您的问题。如果您考虑一下,aPlaylist
可能还有其他属性(例如名称),这些属性在集合上是不可设置的。
Playlists
would then be a collection of Playlist
models (instead of collections), which should work without error.
Playlists
然后将是一个Playlist
模型集合(而不是集合),它应该可以正常工作。
var Track = Backbone.Model.extend({
//trackdata
});
var Playlist = Backbone.Model.extend({
model : Track
});
var Playlists = Backbone.Collection.extend({
url : "playlists",
model : Playlist
});