2010-01-06 00:36:58 +00:00
|
|
|
// Copyright (C) 2009 BRAT Tech LLC
|
|
|
|
|
|
|
|
|
|
// Single $ is special and does not get searched
|
|
|
|
|
// Double $$ is special an is client only (does not get sent to server)
|
|
|
|
|
|
2010-01-09 23:02:43 +00:00
|
|
|
Model = function(entity, initial) {
|
2010-01-06 00:36:58 +00:00
|
|
|
this.$$entity = entity;
|
|
|
|
|
this.$loadFrom(initial||{});
|
|
|
|
|
this.$entity = entity.title;
|
|
|
|
|
this.$migrate();
|
|
|
|
|
};
|
|
|
|
|
|
2010-01-09 23:02:43 +00:00
|
|
|
Model.copyDirectFields = function(src, dst) {
|
2010-01-06 00:36:58 +00:00
|
|
|
if (src === dst || !src || !dst) return;
|
|
|
|
|
var isDataField = function(src, dst, field) {
|
|
|
|
|
return (field.substring(0,2) !== '$$') &&
|
|
|
|
|
(typeof src[field] !== 'function') &&
|
|
|
|
|
(typeof dst[field] !== 'function');
|
|
|
|
|
};
|
|
|
|
|
for (var field in dst) {
|
|
|
|
|
if (isDataField(src, dst, field))
|
|
|
|
|
delete dst[field];
|
|
|
|
|
}
|
|
|
|
|
for (field in src) {
|
|
|
|
|
if (isDataField(src, dst, field))
|
|
|
|
|
dst[field] = src[field];
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2010-01-09 23:02:43 +00:00
|
|
|
Model.prototype.$migrate = function() {
|
|
|
|
|
merge(this.$$entity.defaults, this);
|
2010-01-06 00:36:58 +00:00
|
|
|
return this;
|
|
|
|
|
};
|
|
|
|
|
|
2010-01-09 23:02:43 +00:00
|
|
|
Model.prototype.$merge = function(other) {
|
|
|
|
|
merge(other, this);
|
2010-01-06 00:36:58 +00:00
|
|
|
return this;
|
|
|
|
|
};
|
|
|
|
|
|
2010-01-09 23:02:43 +00:00
|
|
|
Model.prototype.$save = function(callback) {
|
2010-01-06 00:36:58 +00:00
|
|
|
this.$$entity.datastore.save(this, callback === true ? undefined : callback);
|
|
|
|
|
if (callback === true) this.$$entity.datastore.flush();
|
|
|
|
|
return this;
|
|
|
|
|
};
|
|
|
|
|
|
2010-01-09 23:02:43 +00:00
|
|
|
Model.prototype.$delete = function(callback) {
|
2010-01-06 00:36:58 +00:00
|
|
|
this.$$entity.datastore.remove(this, callback === true ? undefined : callback);
|
|
|
|
|
if (callback === true) this.$$entity.datastore.flush();
|
|
|
|
|
return this;
|
|
|
|
|
};
|
|
|
|
|
|
2010-01-09 23:02:43 +00:00
|
|
|
Model.prototype.$loadById = function(id, callback) {
|
2010-01-06 00:36:58 +00:00
|
|
|
this.$$entity.datastore.load(this, id, callback);
|
|
|
|
|
return this;
|
|
|
|
|
};
|
|
|
|
|
|
2010-01-09 23:02:43 +00:00
|
|
|
Model.prototype.$loadFrom = function(other) {
|
|
|
|
|
Model.copyDirectFields(other, this);
|
2010-01-06 00:36:58 +00:00
|
|
|
return this;
|
|
|
|
|
};
|
|
|
|
|
|
2010-01-09 23:02:43 +00:00
|
|
|
Model.prototype.$saveTo = function(other) {
|
|
|
|
|
Model.copyDirectFields(this, other);
|
2010-01-06 00:36:58 +00:00
|
|
|
return this;
|
|
|
|
|
};
|