forked from tzeikob/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
57 lines (45 loc) · 1.12 KB
/
index.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
// Use your own namespace to keep global scope clean
var myNS = myNS || Object.create(null);
// Let say we have an entity which collecting items
myNS.Entity = function Entity() {
this.items = {};
this.commands = [];
};
myNS.Entity.prototype.get = function get(key) {
return this.items[key];
};
myNS.Entity.prototype.add = function add(item) {
this.items[item.key] = item;
return item;
};
// Add method to call a command given its method name
myNS.Entity.prototype.execute = function execute(name, ...args) {
if (this[name]) {
// Register the command so to be able to rollback
this.commands.push({
name,
args
});
return this[name].apply(this, args);
}
return false;
};
// Add a replay method to execute all the commands as a rollback
myNS.Entity.prototype.replay = function replay() {
this.commands.forEach(c => {
this[c.name].apply(this, c.args);
});
};
let e = new myNS.Entity();
e.execute('add', {
key: 1,
value: 333
});
e.execute('add', {
key: 2,
value: 445
});
// Let say something catastrophic happend
e.items = {};
// You can replay to rollback the state
e.replay();