Skip to content

Instantly share code, notes, and snippets.

@karlwestin
Created April 15, 2012 14:22
Show Gist options
  • Save karlwestin/2393106 to your computer and use it in GitHub Desktop.
Save karlwestin/2393106 to your computer and use it in GitHub Desktop.
Nested models/collections and storage with Backbone.js and Backbone.LocalStorage
/*
* Example of using nested collections/models with backbone.js and backbone.js localStorage
*
* Read the complete blog post at karlwestin.posterous.com
*
* 1. run populate() from command line first time
* 2. reload the page (or open in another browser tab), and check the following:
*
* premier.at(0).get("name") => "Tottenham"
* premier.at(0).players.length => 3
*
*/
var teams = [{ name: "Tottenham" }, { name: "Manchester United" }],
players1 = [{ name: "Ryan Giggs" }, { name: "Wayne Rooney" }, { name: "Michael Owen" }],
players2 = [{ name: "Emmanuel Adebayor" }, { name: "Ledley King" }, { name: "Rafael van der Vaart" }],
Team,
League,
premier
Team = Backbone.Model.extend({
initialize: function(config) {
this.players = new (Backbone.Collection.extend({
localStorage: new Backbone.LocalStorage(config.name)
}))()
this.players.fetch()
},
saveAll: function() {
_.each(this.players.models, function(player) {
player.save()
})
},
add: function(models) {
this.players.add(models)
}
})
League = Backbone.Collection.extend({
localStorage: new Backbone.LocalStorage("league"),
model: Team,
saveAll: function() {
_.each(this.models, function(team) {
team.save()
team.saveAll()
})
}
})
premier = new League()
premier.fetch()
function populate() {
premier.add(teams[0])
premier.add(teams[1])
premier.at(0).add(players2)
premier.at(1).add(players1)
premier.saveAll()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment