2

我正在尝试使用主干编写我的应用程序,但我对它还很陌生。我的应用程序基本上是向用户展示他所有的照片和相册。我对它的设计有一些疑问。

从照片开始是模特的明显候选人。所以

var Photo = Backbone.Model.extend({})

然后我创建了一组照片。

var PhotoCollection = Backbone.Collection.extend({})

这是为了向用户显示“所有照片”、“特定日期上传的照片”等(注意它与相册不同)

现在我的问题是关于专辑,专辑是模型还是收藏?

在相册视图中,我将在网格布局中向用户展示他的所有相册,其中包含照片数量和相册名称以及其他一些属性。因此,将专辑作为 Backbone 模型并将专辑集合作为 Backbone 集合是有意义的。

但是当用户点击相册时,我必须请求该相册中的所有照片。所以,专辑就变成了收藏。但是如果我将专辑写成集合,我如何表示一组专辑?它会是一个集合吗?

我希望这听起来不会令人困惑。

4

1 回答 1

5

根据经验, 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.

于 2013-01-07T20:32:45.357 回答