-
Notifications
You must be signed in to change notification settings - Fork 25
/
CJNotification.js
64 lines (57 loc) · 1.71 KB
/
CJNotification.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
/*
* @Description: 通知工具类:1)Native ➡ JavaScript;2)JavaScript ➡ JavaScript
* @Author: cookiej
* @Date: 2018-05-19 14:47:01
* @Last Modified by: cookiej
* @Last Modified time: 2018-05-19 15:39:07
*/
import {
NativeEventEmitter,
NativeModules,
Platform,
DeviceEventEmitter,
} from 'react-native';
const { CJNotificationCenter } = NativeModules;
const emitter = Platform.OS === 'android' ? new NativeEventEmitter() : new NativeEventEmitter(CJNotificationCenter);
const NativeEventName = 'NATIVE_TO_RN';
class Emitter {
/**
* 监听从 Native 发来的事件
* @param event 事件名称
* @param callback 监听回调
* @function dispose 销毁监听对象
*/
static addNativeListener = (event, callback) => {
const subscription = emitter.addListener(
NativeEventName,
reminder => {
const { eventName, body } = reminder;
if (eventName !== event) return;
callback && callback(body);
},
);
subscription.dispose = () => subscription && subscription.remove();
return subscription;
};
/**
* 监听不同 RN 页面的通知事件
* @param event 事件名称
* @param callback 监听回调
* @function dispose 销毁监听对象
*/
static addRNListener = (event, callback) => {
const subscription = DeviceEventEmitter.addListener(
event,
reminder => callback && callback(reminder),
);
subscription.dispose = () => subscription && subscription.remove();
return subscription;
};
/**
* 发送 RN 页面之间的通知
* @param event 事件名称
* @param body 发送内容
*/
static sendRNEvent = (event, body) => DeviceEventEmitter.emit(event, body);
}
export default Emitter;