Skip to content

Commit

Permalink
Update instance properties after every query
Browse files Browse the repository at this point in the history
  • Loading branch information
notheotherben committed Dec 11, 2013
1 parent da21751 commit 26c883f
Showing 1 changed file with 36 additions and 24 deletions.
60 changes: 36 additions & 24 deletions lib/Instance.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,34 +29,40 @@ function Instance(model, doc, isNew) {

var oldDoc = _.cloneDeep(doc);
var newDoc = _.cloneDeep(doc);

var schema = {};

for(var property in doc)
schema[property] = false;

for(var property in model.schema)
schema[property] = model.schema[property];
var schema = {};

for(var targetProperty in schema) {
(function(targetProperty) {
Object.defineProperty($, targetProperty, {
get: function() {
/// <value type="Object">Get the most recent value for this field</value>
return newDoc[targetProperty];
},
set: function(value) {
/// <value type="Object">Set the value of this field. Changes may be committed by calling save() on this instance.</value>
var validation = validate(schema[targetProperty], value, targetProperty, model.extraValidators);
if (!validation.passed) throw validation.toError();

newDoc[targetProperty] = value;
},
enumerable: true
});
})(targetProperty);
function addSchemaProperties() {

for(var property in newDoc)
schema[property] = false;

for(var property in model.schema)
schema[property] = model.schema[property];

for(var targetProperty in schema) {
if(!$.hasOwnProperty(targetProperty))
(function(targetProperty) {
Object.defineProperty($, targetProperty, {
get: function() {
/// <value type="Object">Get the most recent value for this field</value>
return newDoc[targetProperty];
},
set: function(value) {
/// <value type="Object">Set the value of this field. Changes may be committed by calling save() on this instance.</value>
var validation = validate(schema[targetProperty], value, targetProperty, model.extraValidators);
if (!validation.passed) throw validation.toError();

newDoc[targetProperty] = value;
},
enumerable: true
});
})(targetProperty);
}
}

addSchemaProperties();

for (var methodName in model.options.methods) {
(function (methodName) {
Object.defineProperty($, methodName, {
Expand Down Expand Up @@ -127,6 +133,8 @@ function Instance(model, doc, isNew) {
transform.down(options.transforms, inserted);

oldDoc = newDoc = inserted;

addSchemaProperties();

isNew = false;

Expand Down Expand Up @@ -163,6 +171,8 @@ function Instance(model, doc, isNew) {
newDoc = _.clone(updated);
oldDoc = _.clone(updated);

addSchemaProperties();

return cb(null, $);
});
} else return cb(null, $);
Expand Down Expand Up @@ -202,6 +212,8 @@ function Instance(model, doc, isNew) {

oldDoc = newDoc = updated;

addSchemaProperties();

if(callback) return callback(null, $);
});
}
Expand Down

0 comments on commit 26c883f

Please sign in to comment.