Backbone-associations : save and fetch
Backbone associations recipes: simple save and fetch
by jdkanani
HTML
<script src="http://documentcloud.github.com/underscore/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<script src="http://dhruvaray.github.com/backbone-associations/backbone-associations.js"></script>
<div id="result">
<div>
<b>Results:</b>
</div>
</div>
CSS
body { white-space: pre; font-family: monospace; }
#result {
margin-left: 10px;
}
JavaScript
$(document).ready(function(){
/**
* Show result
*/
function show(r){
var resultDiv=$("#result");
resultDiv.append(r);
resultDiv.append('<br/><br/>');
}
console.log = function(r){
if (typeof r === 'object') {
show(JSON.stringify(r, null, 4));
} else {
show(r);
}
};
/**
* Gist: https://gist.github.com/jdkanani/5822296
*/
var MyApp = {
context: {}
};
MyApp.context.departments = null;
MyApp.context.employees = null;
var counter = 100;
/**
* Initialization of associated models
*/
var Location = Backbone.AssociatedModel.extend({
defaults:{
id:-1,
add1:"",
add2:null,
zip:"",
state:""
},
urlRoot: '/location'
});
var Locations = Backbone.Collection.extend({
model: Location,
url: function() {
return '/locations';
}
});
var Department = Backbone.AssociatedModel.extend({
initialize: function(){
var dept = this;
this.get('locations').url = function(){
return '/department/' + dept.id + '/locations';
}
},
relations:[
{
type:Backbone.Many,
key:'locations',
collectionType: Locations
}
],
defaults:{
name:'',
number:-1
},
urlRoot: '/department'
});
var Departments = Backbone.Collection.extend({
model: Department,
comparator: function(d){
return d.get('number');
},
url: '/departments',
sync: function(method, collection, options) {
return options.success.call(this, [
{id:1, name:"sales", number: 21, locations:[{id:'l1', zip:...