根据经验, aBackbone.Collection
应该映射到一个 REST 集合资源,并且 a 映射到该集合Model
中的一个项目。这不是绝对必要的,但 Backbone 的大部分内容都是围绕这种思维方式构建的。这是一个例子:
/photos -> PhotoCollection
/photos/id -> Photo
/albums -> AlbumCollection
/albums/id -> Album
如果你有这样一个清晰的 RESTful 结构,那么我建议你构建你的模型结构来镜像它。
When you start building relations between different models, Backbone is not so opinionated, and you're free to set things up the way you want. Often it's simplest to think of relations between different models in terms of is
and has
relations. In you case it's a little bit tricky, because one could think that Album is a collection of photos
, but also that Album has photos
.
I would lean towards a has
relationship here, mainly because an Album
probably is more than just a collection of photos - it will have a title and other such properties of its own. In RESTful terms a collection cannot have any properties of its own. So we say that Album has a PhotoCollection
.
Let's say these are your Photo
and PhotoCollection
:
var Photo = Backbone.Model.extend({});
var PhotoCollection = Backbone.Collection.extend({
model: Photo,
filterByDate: function(date) {
//just some method
return this.filter(function(photo) { return photo.get('date') === date; });
}
});
And similarly an Album
and AlbumCollection
.
var Album = Backbone.Model.extend({
initialize: function(attributes) {
//make model.photos a PhotoCollection and initialize it with passed photos
this.set('photos', new PhotoCollection(attributes.photos || []);
}
});
var AlbumCollection = Backbone.Collection.extend({
model: Album
});
Then you can access album's photos just like you would any other collection of photos:
album.get('photos').filterByDate('2012-12-24');
If you need the albums PhotoCollection
to have different behavior from a normal PhotoCollection
, you can simply extend from base collection and use it instead.
var AlbumPhotoCollection = PhotoCollection.extend({ ... });
It's hard to speculate further without knowing more about how your application looks, but in any case this would feel like a natural way of doing it.