The returned JSON is not what Backbone or Backbone-Relational expects by default.
Waiting for Backbone and Backbone-Relational is:
{ "id": "123456", "Title":"Mr", "FirstName":"Joe", "Surname":"Bloggs", "Bookings": [ { "id": "585462542", "EventName": "Bla", "Location":"Dee Bla", "EventDate":"November 1, 2012" }, { "id": "585462543", "EventName": "Bla", "Location":"Dee Bla", "EventDate":"November 1, 2012" } ] }
To use your answer, you need to create a parse function on the client model, which will return the structure published above.
JsFiddle example for your model definitions working with my JSON example: http://jsfiddle.net/edwardmsmith/jVJHq/4/
Other notes
- The trunk expects the
ID fields to be called "id" by default. To use another field as an ID for the model, use Model.idAttribute - The "key" for the collection of orders I changed to "Orders"
Code example:
Client = Backbone.RelationalModel.extend({ urlRoot: '/URL-THAT-RETURNS-JSON/', relations: [ { type: Backbone.HasMany, key: 'Bookings', relatedModel: 'Booking', collectionType: 'BookingsCollection' } ], parse: function (response) { }, initialize: function (options) { console.log(this, 'Initialized'); } }); Booking = Backbone.RelationalModel.extend({ initialize: function (options) { console.log(this, 'Initialized'); } }); BookingsCollection = Backbone.Collection.extend({ model: Booking }); myClient = new Client( { "id": "123456", "Title":"Mr", "FirstName":"Joe", "Surname":"Bloggs", "Bookings": [ { "id": "585462542", "EventName": "Bla", "Location":"Dee Bla", "EventDate":"November 1, 2012" }, { "id": "585462543", "EventName": "Bla", "Location":"Dee Bla", "EventDate":"November 1, 2012" } ] }); console.log(myClient);β
Post Editing
Yes, JSON pretty much defines model attributes. You can use a combination of parse() , defaults , validate() to better control which attributes are valid and allowed.
The canonical way to read and set properties on the base model is get() , escape() and set() functions.
set especially important, as it does a bunch of housekeeping, for example, checking an attribute and value against your validate function (if any) and triggering change events for the model that your views will view.
In the specific case of the situation in this answer you can
myClient.get('Title'); // => "Mr" myClient.get('Bookings'); //=> an instance of a BookingsCollection with 2 models. myClient.get('Bookings').first().get('Location'); //=> "Dee Bla" myClient.get('Bookings').last().get('Location'); //=> "Dee Bla" myClient.get('Bookings').first().set({location:"Bora Bora"}); myClient.get('Bookings').first().get('Location'); //=> "Bora Bora" myClient.get('Bookings').last().get('Location'); //=> "Dee Bla"