Skip to content

Instantly share code, notes, and snippets.

@karlwestin
Created January 24, 2013 20:50
Show Gist options
  • Save karlwestin/4627583 to your computer and use it in GitHub Desktop.
Save karlwestin/4627583 to your computer and use it in GitHub Desktop.
example with the parse method, for nesting a backbone collection inside a model
//example data format:
var data = {
"1": [ { data: 10 }, { data: 11}, { data: 12}],
"2": value,
"3": value2
};
var MyModel = Backbone.Model.extend({
constructor: function() {
arguments[1] = arguments[1] || {}; // ensure there's 'options'
arguments[1].parse = true; // this model should always be parsed on intialization
Backbone.Model.apply(this, arguments)
}
initialize: function() {
this.crazyAssCollection = new Backbone.Collection();
}
parse: function(data) {
// because we enforce parse in the constructor,
// this will always be called
// on initialization
// backbone users this on model.fetch() as well
// add with merge makes sure old models are updated
this.crazyAssCollection.add(data["1"], { merge: true });
delete data["1"];
return data;
}
});
new MyModel(data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment