forked from canjs/can-define-backup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
can-define-backup.js
68 lines (59 loc) · 1.74 KB
/
can-define-backup.js
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
66
67
68
//allows you to backup and restore a map instance
var compare = require('can-set/src/compare');
var assign = require('can-assign');
var canReflect = require('can-reflect');
var SimpleObservable = require('can-simple-observable');
var flatProps = function (a, cur) {
var obj = {};
for (var prop in a) {
if (typeof a[prop] !== 'object' || a[prop] === null || a[prop] instanceof Date) {
obj[prop] = a[prop];
} else {
obj[prop] = cur[prop];//cur.attr(prop);
}
}
return obj;
};
var observables = new WeakMap();
function getBackup(map) {
var obs = observables.get(map);
if(!obs) {
obs = new SimpleObservable();
observables.set(map, obs);
}
return obs;
}
function defineBackup(Map) {
assign(Map.prototype, {
backup: function () {
var store = getBackup(this);
canReflect.setValue(store, this.serialize());
return this;
},
isDirty: function (checkAssociations) {
var store = getBackup(this);
var backupStore = canReflect.getValue(store);
if(!backupStore){
return false;
}
var currentValue = this.serialize();
var aParent, bParent, parentProp;
var compares = {};
var options = { deep: !! checkAssociations };
return !compare.equal(currentValue, backupStore, aParent, bParent, parentProp, compares, options);
},
restore: function (restoreAssociations) {
var store = getBackup(this);
var curVal = canReflect.getValue(store);
var props = restoreAssociations ? curVal : flatProps(curVal, this);
if (this.isDirty(restoreAssociations)) {
for(var prop in props) {
this[prop] = props[prop];
}
}
return this;
}
});
return;
}
module.exports = exports = defineBackup;