主干关系未正确设置反向关系



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

基本上我有骨干SearchService模型。搜索具有包含许多服务的ServiceList集合。

但是,我似乎无法从服务初始值设定项中访问父搜索。当我尝试记录父搜索时,我得到null.谁能看出我做错了什么?

我的搜索模型是这样设置的(代码可能有语法错误,我正在动态翻译咖啡脚本):

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')

简答题

您根本无法访问服务的初始化方法中的反向关系的值。

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

更长的答案

假设这个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/

相关内容

  • 没有找到相关文章