Last active
December 22, 2015 03:29
-
-
Save dhruvaray/6410978 to your computer and use it in GitHub Desktop.
Setup Explicit Reverse Relationships
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}} | |
//]}" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See discussion here as well...