UNPKG

2.72 kBJavaScriptView Raw
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
11'use strict';
12
13const invariant = require('invariant');
14
15import type EventSubscription from 'EventSubscription';
16
17/**
18 * EventSubscriptionVendor stores a set of EventSubscriptions that are
19 * subscribed to a particular event type.
20 */
21class EventSubscriptionVendor {
22 _subscriptionsForType: Object;
23 _currentSubscription: ?EventSubscription;
24
25 constructor() {
26 this._subscriptionsForType = {};
27 this._currentSubscription = null;
28 }
29
30 /**
31 * Adds a subscription keyed by an event type.
32 *
33 * @param {string} eventType
34 * @param {EventSubscription} subscription
35 */
36 addSubscription(
37 eventType: string,
38 subscription: EventSubscription,
39 ): EventSubscription {
40 invariant(
41 subscription.subscriber === this,
42 'The subscriber of the subscription is incorrectly set.',
43 );
44 if (!this._subscriptionsForType[eventType]) {
45 this._subscriptionsForType[eventType] = [];
46 }
47 const key = this._subscriptionsForType[eventType].length;
48 this._subscriptionsForType[eventType].push(subscription);
49 subscription.eventType = eventType;
50 subscription.key = key;
51 return subscription;
52 }
53
54 /**
55 * Removes a bulk set of the subscriptions.
56 *
57 * @param {?string} eventType - Optional name of the event type whose
58 * registered supscriptions to remove, if null remove all subscriptions.
59 */
60 removeAllSubscriptions(eventType: ?string) {
61 if (eventType === undefined) {
62 this._subscriptionsForType = {};
63 } else {
64 delete this._subscriptionsForType[eventType];
65 }
66 }
67
68 /**
69 * Removes a specific subscription. Instead of calling this function, call
70 * `subscription.remove()` directly.
71 *
72 * @param {object} subscription
73 */
74 removeSubscription(subscription: Object) {
75 const eventType = subscription.eventType;
76 const key = subscription.key;
77
78 const subscriptionsForType = this._subscriptionsForType[eventType];
79 if (subscriptionsForType) {
80 delete subscriptionsForType[key];
81 }
82 }
83
84 /**
85 * Returns the array of subscriptions that are currently registered for the
86 * given event type.
87 *
88 * Note: This array can be potentially sparse as subscriptions are deleted
89 * from it when they are removed.
90 *
91 * TODO: This returns a nullable array. wat?
92 *
93 * @param {string} eventType
94 * @returns {?array}
95 */
96 getSubscriptionsForType(eventType: string): ?[EventSubscription] {
97 return this._subscriptionsForType[eventType];
98 }
99}
100
101module.exports = EventSubscriptionVendor;