-
Notifications
You must be signed in to change notification settings - Fork 1
/
atom.js
52 lines (41 loc) · 913 Bytes
/
atom.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
function Atom(state) {
this.state = state;
this.watches = {};
}
Atom.prototype = {
addWatch: function(k, f) {
this.watches[k] = f;
return this;
},
removeWatch: function(k) {
delete this.watches[k];
return this;
},
swap: function(f) {
return this.mswap.apply(
this,
[undefined, f].concat([].slice.call(arguments, 1))
);
},
mswap: function(meta, f) {
return this.mreset(
meta,
f.apply(null, [this.state].concat([].slice.call(arguments, 2)))
);
},
reset: function(state) {
return this.mreset(undefined, state);
},
mreset: function(meta, state) {
var watches = this.watches;
var oldState = this.state;
this.state = state;
Object.keys(watches).forEach(function(k) {
watches[k](state, oldState, k, meta);
});
return this;
}
}
module.exports = function(state) {
return new Atom(state);
};