How do I save, fetch and manage a nested collection with backbone and
marionette?
I've looked through all the existing information about this, and just
can't get find a complete example or get my head around it - I'm new to
backbone/marionette.
I am using localstorage for persistence. I have a collection of game
models, each game model contains a collection of scorecard models as an
attribute.
var GameList = (function(){
return Backbone.Collection.extend({
model: Game,
localStorage: new Backbone.LocalStorage('datastore')});
var Game = Backbone.Model.extend({
localStorage: new Backbone.LocalStorage('datastore'),
defaults: {
name : '',
scorecards: new ScorecardList(),
created : 0
},
initialize : function() {
if (this.isNew()) this.set('created', Date.now());
}
});
I fetch the game collection when the app starts and render a list of games.
// Populate the main gamelist here
app.gameList = new GameList();
app.gameList.fetch();
When a game is clicked I pass the game id to a route that does a get of
the scorecard collection for that game and I render a list of scorecards.
So far so good.
game: function(param){
var g = app.gameList.get(param);
var m = new Backbone.Model({showBack:true,showSettings:true,title:
g.get('name')});
var header = new Header({model:m});
app.layout.header.show(header);
app.layout.main.show(new ScorecardListCompositeView({
collection : new ScorecardList(g.get('scorecards')),
model: g,
transitionIn: "fade",
transitionOut: "fade"
}));
The issue I'm having is that I cannot seem to find the right way to then
create a new scorecard within the scorecard collection and save it so that
the scorecard, scorecard collection and game collection are all in sync.
addPlayer: function () {
var s = new Scorecard({playerName:this.ui.playerName.val()});
this.collection.add(s);
//this.model.set({ scorecards: this.collection });
this.model.save({wait:true});
this.hideAddForm();
// NO IDEA WHAT TO DO HERE TO ENSURE CHANGES ARE REFLECTED??
}
It would be much appreciated if someone could point me to an example of
this to look at, I can't really post a fiddle without reworking everything
so I'm hoping this is enough to go on and I can figure it out with a
little nudge via an example.
No comments:
Post a Comment