aboutsummaryrefslogtreecommitdiffstats
path: root/src/Model.js
blob: 35f6a1c108fa3ea46cdda549c18685e8cf494cf5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// 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)

Model = function(entity, initial) {
  this.$$entity = entity;
  this.$loadFrom(initial||{});
  this.$entity = entity.title;
  this.$migrate();
};

Model.copyDirectFields = function(src, dst) {
  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];
  }
};

Model.prototype.$migrate = function() {
  merge(this.$$entity.defaults, this);
  return this;
};

Model.prototype.$merge = function(other) {
  merge(other, this);
  return this;
};

Model.prototype.$save = function(callback) {
  this.$$entity.datastore.save(this, callback === true ? undefined : callback);
  if (callback === true) this.$$entity.datastore.flush();
  return this;
};

Model.prototype.$delete = function(callback) {
  this.$$entity.datastore.remove(this, callback === true ? undefined : callback);
  if (callback === true) this.$$entity.datastore.flush();
  return this;
};

Model.prototype.$loadById = function(id, callback) {
  this.$$entity.datastore.load(this, id, callback);
  return this;
};

Model.prototype.$loadFrom = function(other) {
  Model.copyDirectFields(other, this);
  return this;
};

Model.prototype.$saveTo = function(other) {
  Model.copyDirectFields(this, other);
  return this;
};