UNPKG

2.56 kBtext/x-cView 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#pragma once
8
9#include <memory>
10#include <mutex>
11
12#include <folly/dynamic.h>
13#include <react/events/EventDispatcher.h>
14#include <react/events/primitives.h>
15
16namespace facebook {
17namespace react {
18
19class EventEmitter;
20
21using SharedEventEmitter = std::shared_ptr<const EventEmitter>;
22
23/*
24 * Base class for all particular typed event handlers.
25 * Stores a pointer to `EventTarget` identifying a particular component and
26 * a weak pointer to `EventDispatcher` which is responsible for delivering the
27 * event.
28 */
29class EventEmitter {
30 /*
31 * We have to repeat `Tag` type definition here because `events` module does
32 * not depend on `core` module (and should not).
33 */
34 using Tag = int32_t;
35
36 public:
37 static std::mutex &DispatchMutex();
38
39 static ValueFactory defaultPayloadFactory();
40
41 EventEmitter(
42 SharedEventTarget eventTarget,
43 Tag tag,
44 WeakEventDispatcher eventDispatcher);
45
46 virtual ~EventEmitter() = default;
47
48 /*
49 * Enables/disables event emitter.
50 * Enabled event emitter retains a pointer to `eventTarget` strongly (as
51 * `std::shared_ptr`) whereas disabled one don't.
52 * Enabled/disabled state is also proxied to `eventTarget` where it indicates
53 * a possibility to extract JSI value from it.
54 * The enable state is additive; a number of `enable` calls should be equal to
55 * a number of `disable` calls to release the event target.
56 * `DispatchMutex` must be acquired before calling.
57 */
58 void setEnabled(bool enabled) const;
59
60 protected:
61#ifdef ANDROID
62 // We need this temporarily due to lack of Java-counterparts for particular
63 // subclasses.
64 public:
65#endif
66
67 /*
68 * Initates an event delivery process.
69 * Is used by particular subclasses only.
70 */
71 void dispatchEvent(
72 const std::string &type,
73 const ValueFactory &payloadFactory =
74 EventEmitter::defaultPayloadFactory(),
75 const EventPriority &priority = EventPriority::AsynchronousBatched) const;
76
77 void dispatchEvent(
78 const std::string &type,
79 const folly::dynamic &payload,
80 const EventPriority &priority = EventPriority::AsynchronousBatched) const;
81
82 private:
83 void toggleEventTargetOwnership_() const;
84
85 mutable SharedEventTarget eventTarget_;
86 WeakEventDispatcher eventDispatcher_;
87 mutable int enableCounter_{0};
88 mutable bool isEnabled_{false};
89};
90
91} // namespace react
92} // namespace facebook