4

Backbone.Relationalを使用して、アプリにいくつかの関連付けを設定しようとしています。

基本的に私はバックボーンSearchServiceモデルを持っています。検索には、ServiceList多くのサービスを含むコレクションがあります。

ただし、サービス初期化子内から親検索にアクセスできないようです。親検索をログに記録しようとすると、が表示されますnull。誰かが私が間違っていることを見ることができますか?

私の検索モデルは次のように設定されています(コードに構文エラーがある可能性があります。その場でcoffeescriptから翻訳しています):

var Search = new Backbone.RelationalModel({
  urlRoot: '/searches',

  relations: [{
    type: Backbone.HasMany,
    key: 'services',
    relatedModel: 'Service',
    collectionType: 'ServiceList',
    reverseRelation: {
      key: 'search'
    }
  }],

  initialize: function(options) {
    // => Search "has services:", ServiceList
    console.log this, "has services:", @get('services');
  }
});


var Service = new Backbone.RelationalModel
  initialize: function() {
    // => Service "in" null
    console.log this, "in", @get('search');
  }
});

または、CoffeeScriptを好む場合:

class Search extends Backbone.RelationalModel
  urlRoot: '/searches'

  relations: [
    type: Backbone.HasMany
    key: 'services'
    relatedModel: 'Service'
    collectionType: 'ServiceList'
    reverseRelation:
      key: 'search'
  ]

  initialize: (options) ->
    // => Search "has services:", ServiceList
    console.log this, "has services:", @get('services')



class Service extends Backbone.RelationalModel
  initialize: ->
    // => Service "in" null
    console.log this, "in", @get('search')
4

1 に答える 1

10

簡潔な答え

サービスの初期化メソッドで逆リレーションの値にアクセスできないだけです。

逆リレーションの値は、初期化が完了した後に設定されます。

より長い答え

このJavaScriptを仮定すると:

Search = Backbone.RelationalModel.extend({
  urlRoot: '/searches',

  relations: [{
    type: Backbone.HasMany,
    key: 'services',
    relatedModel: 'Service',
    reverseRelation: {
      key: 'search'
    }
  }],

  initialize: function(options) {
    console.log(this, "has services:", this.get('services'));
  }
});


Service = Backbone.RelationalModel.extend({
  initialize: function() {
    console.log(this, "in", this.get('search'));
  }
});

関連するサービスを使用して新しい検索モデルを作成する場合:

s1 = new Search({name:"Some Search",services:[{name:"service1"},{name:"service2"}]});

何が起こるかは次のとおりです。

new Service model created (for service1) - name set to "service1"
  (but, since what got passed to the model for properties is {name:"service1"}
   you can see how this model cannot know its reverse relation yet.)
new Service model created (for service2) - name set to "service2"
  (same as above)
new Search model created (for 'some search')
  name set to 'some search'
  service1 Service model added to Search.services
    (triggers 'update:search' event on Service1 model)
  service2 Service model added to Search services
    (triggers 'update:search' event on Service2 model)

service1 と service2 Service モデルが Search.services コレクションに追加されるまで、service1.search と service2.search の逆の関係は設定されません。

コンソールでの操作の順序を示す JS フィドルを次に示します: http://jsfiddle.net/MNh7N/6/

于 2012-04-05T14:05:01.687 に答える