I'm trying to use Backbone.Relational to set up some associations in my app.
Basically I have Backbone Search
and Service
models. A Search has a ServiceList
collection which contains many services.
However, I don't seem to be able to access the parent Search from within the Service initializer. When I try to log the parent search I get null
. Can anyone see what I'm doing wrong?
My Search model is set up like so (code might have syntax errors, I'm translating from coffeescript on the fly):
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');
}
});
Or if you prefer 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')