0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Backbone-relationalメモ

Last updated at Posted at 2015-03-10

使い方

逆参照時の取り扱い

includeInJSONの挙動をようやく把握したのでメモ(あんまり興味なかった)。こんな感じ。

class AlbumModel extends Backbone.RelationalModel
  @
  
class PhotoModel extends Backbone.RelationalModel

  relations: [
    {
      # PhotoModelとAlbumModelの関係をが 1:N とする
      type: Backbone.HasOne
      relatedModel: AlbumModel
      
      # photoModel.get('album') でAlbumModelを取得
      key: 'album'
      
      # albumModelからどう見えるか
      reverseRelation:
        # albumModel.get('photos') としてPhotoModelを取得
        key: 'photos'
        # albumModel.get('photos') として取得した場合に含めるのはidのみ
        includeInJSON: ['id']
    }
  ]

# e.g.
album = new AlbumModel(id: 1)
album.fetch()

# snip
photos = album.get('photos')

photo = photos[0]
photo.attributes

###
{
  id: 123
}
###

トラブルシュート

連携先のコレクションが常にBackbone.Collectionになる

例えばこんなふうに、2つのファイルに分かれている。

class Photo extends Backbone.RelationalModel
  idAttribute: 'id'
  urlRoot: '/ajax/photos/'
  
class PhotoCollection extends Backbone.Collection
  model: Photo
album.coffee
class Album extends Backbone.RelationalModel
  idAttribute: 'id'
  urlRoot: '/ajax/albums/'
  relations: [
    {
      type: Backbone.HasMany,
      key: 'photos',
      relatedModel: Photo,
      collectionType: PhotoCollection
    }
  ]

Albumを初期化してphotosを取り出すと、collectionがBackbone.Collectionになった。

view.coffee
album = new Album(id: 1)
collection = album.get('photos')  # これがBackbone.Collectionになる!

album.coffee内でPhotoCollectionが参照できないためBackbone.Collectionが返る。Collectionオブジェクトが返ってくるので一見普通に動いているように見えてしまうのがクセモノ。色々調べた結果、album.coffeephoto.coffeeをrequireしていないのが原因だった。ショボイ。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?