4

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

基本上我有 BackboneSearchService模型。搜索有一个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 服务模型添加到 Search.services 集合中,才设置了 service1.search 和 service2.search 的反向关系。

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

于 2012-04-05T14:05:01.687 回答