Skip to content

Instantly share code, notes, and snippets.

@dhruvaray
Last active December 22, 2015 03:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhruvaray/6410978 to your computer and use it in GitHub Desktop.
Save dhruvaray/6410978 to your computer and use it in GitHub Desktop.
Setup Explicit Reverse Relationships
var MyApp = {
Models:{}
};
var Models = MyApp.Models;
Models.Zoo = Backbone.AssociatedModel.extend({
relations: [{
type: Backbone.Many,
key: 'animals',
relatedModel: 'Models.Animal'
}],
//Simulation
sync:function (method, model, options) {
var response = {};
if (method === 'create') {
response[model.idAttribute] = counter++; // dummy id
} else if (method === 'update') {
// Let's assume that - after success update, server sends model's json object
response = model.toJSON();
}
return options.success.call(this, response);
}
});
Models.Animal = Backbone.AssociatedModel.extend({
relations: [{
type: Backbone.One,
key: 'livesIn',
relatedModel: 'Models.Zoo'
}]
});
var nyzoo = new Models.Zoo({id:1, name:'NY Zoo'});
nyzoo.set('animals', [
new Models.Animal({id:101, type:'Lion', livesIn:nyzoo}),
new Models.Animal({id:102, type:'Zebra', livesIn:nyzoo}),
new Models.Animal({id:103, type:'Giraffe', livesIn:nyzoo})
]);
nyzoo.save();
//JSON.stringify(nyzoo); would yield
//"{"id":1,"name":"NY Zoo","animals":[
// {"id":101,"type":"Lion","livesIn":{"id":1}},
// {"id":102,"type":"Zebra","livesIn":{"id":1}},
// {"id":103,"type":"Giraffe","livesIn":{"id":1}}
//]}"
@dhruvaray
Copy link
Author

See discussion here as well...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment