NativeEventEmitter.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @format
  8. * @flow
  9. */
  10. 'use strict';
  11. const EventEmitter = require('../vendor/emitter/EventEmitter');
  12. const Platform = require('../Utilities/Platform');
  13. const RCTDeviceEventEmitter = require('./RCTDeviceEventEmitter');
  14. const invariant = require('invariant');
  15. import type EmitterSubscription from '../vendor/emitter/EmitterSubscription';
  16. type NativeModule = {
  17. +addListener: (eventType: string) => void,
  18. +removeListeners: (count: number) => void,
  19. ...
  20. };
  21. /**
  22. * Abstract base class for implementing event-emitting modules. This implements
  23. * a subset of the standard EventEmitter node module API.
  24. */
  25. class NativeEventEmitter extends EventEmitter {
  26. _nativeModule: ?NativeModule;
  27. constructor(nativeModule: ?NativeModule) {
  28. super(RCTDeviceEventEmitter.sharedSubscriber);
  29. if (Platform.OS === 'ios') {
  30. invariant(nativeModule, 'Native module cannot be null.');
  31. this._nativeModule = nativeModule;
  32. }
  33. }
  34. addListener(
  35. eventType: string,
  36. listener: Function,
  37. context: ?Object,
  38. ): EmitterSubscription {
  39. if (this._nativeModule != null) {
  40. this._nativeModule.addListener(eventType);
  41. }
  42. return super.addListener(eventType, listener, context);
  43. }
  44. removeAllListeners(eventType: string) {
  45. invariant(eventType, 'eventType argument is required.');
  46. const count = this.listeners(eventType).length;
  47. if (this._nativeModule != null) {
  48. this._nativeModule.removeListeners(count);
  49. }
  50. super.removeAllListeners(eventType);
  51. }
  52. removeSubscription(subscription: EmitterSubscription) {
  53. if (this._nativeModule != null) {
  54. this._nativeModule.removeListeners(1);
  55. }
  56. super.removeSubscription(subscription);
  57. }
  58. }
  59. module.exports = NativeEventEmitter;