Skip to content

Instantly share code, notes, and snippets.

@smalljam
Created April 21, 2011 13:01
Show Gist options
  • Save smalljam/934432 to your computer and use it in GitHub Desktop.
Save smalljam/934432 to your computer and use it in GitHub Desktop.
Backbone multimodel proof of concept
// make sure underscore.js & backbone.js included above
$ = {ajax: function(){
console.log('BAM!');
console.dir(arguments);
}}
var BaseModel = Backbone.Model.extend({
url: 'whatever',
save: function(attributes, options){
console.log('Im saved');
Backbone.Model.prototype.save.call(this, attributes || this.attributes, options);
},
diff: function(){
}
});
var BaseCollection = Backbone.Collection.extend({
save: function(){
_.each(this.models, function(m){
m.save();
});
}
});
var ModelA = BaseModel.extend({});
var ModelB = BaseModel.extend({});
var ModelC = BaseModel.extend({});
var MultiModel = BaseModel.extend({
modelsMap: {},
set: function(attributes, options){
var that = this;
_.each(attributes, function(v,k){
attributes[k] = k in that.modelsMap ? new that.modelsMap[k](v) : v; // TODO: smart setter
});
BaseModel.prototype.set.call(this, attributes, options);
},
toJSON: function(){
var result = _.clone(this.attributes);
_.each(result, function(v,k){
v['toJSON'] ? result[k] = v.toJSON() : '';
});
return result;
},
save: function(attributes, options){
console.log('multi model save:');
attributes = attributes || this.attributes;
var newAttr = _.clone(attributes);
_.each(attributes, function(v,k){
if(v['save']) {
v.save.call(v);
delete newAttr[k];
}
});
if(JSON.stringify(newAttr) != '{}') {
BaseModel.prototype.save.call(this, newAttr, options);
}
}
});
var MyMultiModel = MultiModel.extend({
modelsMap: {
a: ModelA,
b: ModelB,
c: MultiModel.extend({
modelsMap: {
types: ModelC
}
}),
d: BaseCollection.extend({
model: ModelC
})
},
url: 'myltiModel'
});
var MyCollection = BaseCollection.extend({
model: MyMultiModel,
url: 'myCollection'
});
var c = new MyCollection;
c.add({
a: {a:1, b:2, c:3},
b: {key: 'value'},
c: {types: {t1:11, t2:22, t3:33}},
d: [ {a:1}, {b:2}, {c:3} ],
ops: 'blabla'
});
c.save(); // THERE IS A BUG: MyMultiModel don't save {ops: 'blabla'} itself :(
//console.log( c.at(0).get('c').get('types').get('t1') );
console.log( '\n---- c.toJSON(): -----' );
console.dir( c.toJSON() );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment