Backbone.js集合的集合
我想弄清楚如何用backbone.js制作集合集合。 我对骨干很陌生。 我有这样的情况:
+---------------+ +------------------+ | Playlists | | Playlist | |---------------| 0..* |------------------| | +-------------->| Name | | | | | | | | | +---------------+ +-------+----------+ | | |0..* v +------------------+ | Track | |------------------| | Name | | Artist | | | +------------------+
在代码中,这看起来类似于这样的:
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控制台说:
Uncaught TypeError: Object [object Object] has no method '_validate'
当我尝试执行一个触发validation的函数(如add,fetch,…)
如果我将validate
或_validate
函数添加到任何集合或模型,则没有区别。
我相信这是因为backbone.js不支持集合中的集合。 有另一种方法可行吗?
更新:
这是现在的样子
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
可能会有其他属性(例如名字),这些属性在集合上是无法设置的。
Playlists
将成为Playlist
模型(而不是集合)的集合,这应该没有错误地工作。
var Track = Backbone.Model.extend({ //trackdata }); var Playlist = Backbone.Model.extend({ model : Track }); var Playlists = Backbone.Collection.extend({ url : "playlists", model : Playlist });