50

我试图弄清楚如何使用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'

当我尝试执行触发验证的函数时(如添加、获取、...)

如果我将validateor_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 
});
4

1 回答 1

30

你可以通过将你Playlist的收藏变成模型来解决你的问题。如果您考虑一下,Playlist无论如何 a 可能还有其他无法在集合上设置的属性(例如名称)。

Playlists然后将是Playlist模型的集合(而不是集合),它应该可以正常工作。

var Track = Backbone.Model.extend({
    //trackdata
});

var Playlist = Backbone.Model.extend({
    model : Track
});

var Playlists = Backbone.Collection.extend({
    url   : "playlists",
    model : Playlist
});
于 2012-04-30T18:16:27.760 回答