-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
78 lines (67 loc) · 2.04 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import deepEqual from './utils/deepEqual.js';
import clone from './utils/clone.js';
let store = {};
/**
* Manage a variable accross multiple files
* The data is associated to a "key" (can be anything)
*/
export default {
/**
* Store data into the storage
* @param {*} key: the key under wich the value will be stored
* @param {*} newValue: the associated data
*/
set(key, newValue) {
let prevValue = undefined;
if (!store[key]) {
// New key, let's create it and that's all.
store[key] = { value: clone(newValue), subscribers: [] };
return;
}
prevValue = store[key].value;
if (deepEqual(newValue, prevValue)) {
// If we have a previous value, and if it is the same,
// then we don't notify
return;
}
store[key].value = clone(newValue);
store[key].subscribers.forEach(callback => callback(clone(newValue), clone(prevValue)));
},
/**
* Return the data associated to the key
* @param {*} key
*/
get(key) {
return store[key] ? clone(store[key].value) : undefined;
},
/**
*
* @param {*} key - the key of the data
* @param {function(any, any):void} callback - called when the data chagne
* @param {object} options
* @param {boolean} [options.fireImmediately=false] - if true, the callback is immediately fired with the last stored value
* @returns {function(void):void} - Unregister the listener
*/
subscribe(key, callback, options = {}) {
let index = 1;
if (typeof callback !== 'function') {
console.error(`Registering in duix for '${key}': Callback is not a function: `, callback);
}
// Set the default options
options = {
fireImmediately: false,
...options,
};
if (!store[key]) {
store[key] = { value: undefined, subscribers: [] };
}
index = store[key].subscribers.push(callback);
if (options.fireImmediately) {
callback(this.get(key), undefined);
}
// This returns the unsubscribe handler
return () => {
delete store[key].subscribers[index - 1];
};
},
};