-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.js
113 lines (98 loc) · 2.71 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import {NativeModules, NativeEventEmitter} from 'react-native';
const { RNPreferenceManager } = NativeModules;
const eventEmitter = new NativeEventEmitter(RNPreferenceManager);
const listeners = new Set();
eventEmitter.addListener('SHMPreferenceWhiteListChanged', info => {
for (const key in info) {
const value = info[key];
if (isNil(value)) {
delete PREFERENCES[key];
} else {
try {
const safeValue = JSON.parse(JSON.stringify(value));
PREFERENCES[key] = safeValue;
} catch (error) {
console.warn('wrong format:', value);
}
}
}
for (let listener of listeners) {
listener(info);
}
});
eventEmitter.addListener('SHMPreferenceClear', info => {
if (!isNil(info)) {
//clear key
const key = info['key'];
if (!isNil(PREFERENCES[key])) {
delete PREFERENCES[key];
for (let listener of listeners) {
listener({[key]: null});
}
}
} else {
//clear all
if (Object.keys(PREFERENCES).length !== 0) {
PREFERENCES = {};
for (let listener of listeners) {
listener({});
}
}
}
});
function addPreferenceChangedListener(listener) {
listeners.add(listener);
}
function removePreferenceChangedListener(listener) {
listeners.delete(listener);
}
let PREFERENCES = {};
try {
PREFERENCES = JSON.parse(RNPreferenceManager.InitialPreferences);
} catch (err) {
console.warn(`preference parse exception:${err.message}`);
}
function get(key) {
return isNil(key) ? PREFERENCES : PREFERENCES[key];
}
function set(key, value) {
if (isNil(value)) {
return clear(key);
} else {
try {
const data = {};
const safeValue = JSON.parse(JSON.stringify(value));
PREFERENCES[key] = safeValue;
data[key] = safeValue;
return RNPreferenceManager.set(JSON.stringify(data));
} catch (error) {
return Promise.reject(error);
}
}
}
function clear(key) {
if (isNil(key)) {
PREFERENCES = {};
return RNPreferenceManager.clear();
} else {
delete PREFERENCES[key];
return RNPreferenceManager.set(JSON.stringify({
[key]: null
}));
}
}
// 设置白名单, (需要接收状态发生改变的keys)
function setWhiteList(list) {
RNPreferenceManager.setWhiteList(list);
}
function isNil(value) {
return value === null || value === undefined
}
export default {
addPreferenceChangedListener,
removePreferenceChangedListener,
setWhiteList,
get,
set,
clear,
};