Backbone Relational没有正确设置反向关系?

时间:2012-04-05 12:58:38

标签: javascript backbone.js backbone-relational

我正在尝试使用Backbone.Relational在我的应用中设置一些关联。

基本上我有Backbone 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')

1 个答案:

答案 0 :(得分:10)

简答

您只是无法访问Service的initialize方法中的反向关系值。

反向关系的值在初始化完成后设置。

更长的答案

假设这个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服务模型添加到Search.services集合中,才设置service1.search和service2.search上的反向关系。

这是一个JS小提琴,显示了控制台中的操作顺序:http://jsfiddle.net/MNh7N/6/