Skip to content

Instantly share code, notes, and snippets.

@jhirn
Last active December 18, 2015 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhirn/5815845 to your computer and use it in GitHub Desktop.
Save jhirn/5815845 to your computer and use it in GitHub Desktop.
App.Models.BaseModel = Backbone.Model.extend({
preParse: function(data){},
constructor: function(attributes, options){
options = options || {};
options.parse = true;
Backbone.Model.call(this, attributes, options);
},
wrapAttribute: function(attributes, key, backboneType) {
var value = attributes[key];
if (attributes[key] && isNotTypeOf(backboneType, value)) {
attributes[key] = new backboneType(value);
}
},
parse: function(data, options){
this.preParse(data);
return data;
}
});
App.Models.Team = App.Models.BaseModel.extend({
preParse: function(data){
this.wrapAttribute(data,'roster',App.Collections.Players);
}
});
App.Models.Player = App.Models.BaseModel.extend({});
App.Collections.Players = Backbone.Collection.extend({
model: App.Models.Player
});
var team = new App.Models.Team({
name: "Bulls",
city: "Chicago",
roster: [{name: "Derrick Rose"}, {name: "Joakim Noah"}]
});
var player1 = team.get('roster').first();
player1.get('name'); // => "Derrick Rose"
player1.set('name', "D. Rose");
player1.save();
App.Models.Team = Backbone.Model.extend({
defaults: {
roster: new App.Collections.Players
}
});
App.Models.Team = Backbone.Model.extend({
defaults: function(){
return {roster: new App.Collections.Players};
}
});
var team1 = new App.Models.Team;
var team2 = new App.Models.Team;
team1.get('roster').add(new App.Models.Player);
team1.get('roster').size(); // => 1, That's fine
team2.get('roster').size(); // => 0, Yes!
(new App.Models.Team).get('roster').size(); // => 0 Expected!
var team1 = new App.Models.Team;
var team2 = new App.Models.Team;
team1.get('roster').add(new App.Models.Player);
team1.get('roster').size(); // => 1, That's fine
team2.get('roster').size(); // => 1, That's totally not fine
(new App.Models.Team).get('roster').size(); // => 1, That's just weird
// In app/assets/javascripts/models/user.js
App.Models.User = Backbone.Model.extend({
urlRoot: '/url-goes-here'
});
App.Collections.Users = Backbone.Collection.extend({
url: '/url-goes-here',
model: App.Models.User
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment