Skip to content

Commit

Permalink
partial saves fully implemented, handles complex structures, casting,…
Browse files Browse the repository at this point in the history
… nested objects.
  • Loading branch information
nw committed Aug 8, 2010
1 parent aaab4b8 commit 779f3af
Showing 1 changed file with 42 additions and 3 deletions.
45 changes: 42 additions & 3 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,14 @@ Model = this.Model = Class({
this.__doc._id = new ObjectID();
this.isNew = true;
this._dirty = {};
this._partials = {};
if (hydrate){
this._hydrate(doc);
} else if(doc){
this.merge(doc);
}
}
this._diff();
return this;
},

_hydrate: function(doc){
Expand All @@ -26,6 +29,20 @@ Model = this.Model = Class({
return this;
},

_diff: function(){
var keys = Object.keys(this.__doc),
casters = Object.keys(this._casters),
exclude = {};

for(var i = 0, l = casters.length; i < l; i++){
this._partials[casters[i]] = JSON.stringify(this._get(casters[i]));
}

for(var i = 0, l = keys.length; i < l; i++){
this._partials[keys[i]] = JSON.stringify(this.__doc[keys[i]]);
}
},

_error: function(err){
this.emit('error', err);
},
Expand Down Expand Up @@ -114,9 +131,31 @@ Model = this.Model = Class({
},

_getDirty: function(){

var _doc = this._normalize(),
dirty = {}, dirt;
for(dirt in this._dirty) dirty[dirt] = this._get(dirt);
dirty = {}, dirt, exclude = {};
for(dirt in this._dirty){
var data = this._get(dirt), comp, part;
if(this._partials[dirt]){
if(this._partials[dirt] != (comp = JSON.stringify(data))){
dirty[dirt] = data; this._partials[dirt] = comp;
}
} else { dirty[dirt] = this._partials[dirt] = data; }
parts = dirt.split('.');
while(parts.pop() && parts.length)
exclude[parts.join('.')] = true;
}

var keys = Object.keys(this._partials);
for(var i = 0, l = keys.length; i < l; i++){
if(!exclude[keys[i]]){
var obj = this._get(keys[i]), comp = JSON.stringify(obj);
if(comp != this._partials[keys[i]]){
dirty[keys[i]] = obj;
this._partials[keys[i]] = comp;
}
}
}
return dirty;
},

Expand Down

0 comments on commit 779f3af

Please sign in to comment.