UNPKG

2.35 kBJavaScriptView Raw
1import invariant from 'invariant';
2import { NativeEventEmitter, Platform } from 'react-native';
3const nativeEmitterSubscriptionKey = '@@nativeEmitterSubscription@@';
4export class EventEmitter {
5 constructor(nativeModule) {
6 this._listenerCount = 0;
7 this._nativeModule = nativeModule;
8 this._eventEmitter = new NativeEventEmitter(nativeModule);
9 }
10 addListener(eventName, listener) {
11 if (!this._listenerCount && Platform.OS !== 'ios' && this._nativeModule.startObserving) {
12 this._nativeModule.startObserving();
13 }
14 this._listenerCount++;
15 const nativeEmitterSubscription = this._eventEmitter.addListener(eventName, listener);
16 const subscription = {
17 [nativeEmitterSubscriptionKey]: nativeEmitterSubscription,
18 remove: () => {
19 this.removeSubscription(subscription);
20 },
21 };
22 return subscription;
23 }
24 removeAllListeners(eventName) {
25 const removedListenerCount = this._eventEmitter.listeners(eventName).length;
26 this._eventEmitter.removeAllListeners(eventName);
27 this._listenerCount -= removedListenerCount;
28 invariant(this._listenerCount >= 0, `EventEmitter must have a non-negative number of listeners`);
29 if (!this._listenerCount && Platform.OS !== 'ios' && this._nativeModule.stopObserving) {
30 this._nativeModule.stopObserving();
31 }
32 }
33 removeSubscription(subscription) {
34 const nativeEmitterSubscription = subscription[nativeEmitterSubscriptionKey];
35 if (!nativeEmitterSubscription) {
36 return;
37 }
38 this._eventEmitter.removeSubscription(nativeEmitterSubscription);
39 this._listenerCount--;
40 // Ensure that the emitter's internal state remains correct even if `removeSubscription` is
41 // called again with the same subscription
42 delete subscription[nativeEmitterSubscriptionKey];
43 // Release closed-over references to the emitter
44 subscription.remove = () => { };
45 if (!this._listenerCount && Platform.OS !== 'ios' && this._nativeModule.stopObserving) {
46 this._nativeModule.stopObserving();
47 }
48 }
49 emit(eventName, ...params) {
50 this._eventEmitter.emit(eventName, ...params);
51 }
52}
53//# sourceMappingURL=EventEmitter.js.map
\No newline at end of file