I. What is an Event Emitter?
An event emitter
is a utility object, which can be used to emit event, which can be subscribed by as many functions as we can.
It is an event manager, manages differents event and its subscribers.
Also, we can see it as the
Redux
, which also dispatches(emits) actions, and handled by its reducers.- It widely used at Node.js ( asynchronous event-driven architecture)
- certain kind of objects call emitters periodically to emit events that cause listener objects to be called.
- when a request comes requesting some resource, Node.js will register the subscriber:
responseToThisRequest()
on event:thisTypeDataDone
. When data is obtained, will callemitter.emit( thisTypeDataDone )
, to call theresponseToThisRequest()
corresponding all the requests.
II. Why and when do we need it?
Whenever it makes sense for code to SUBSCRIBE to something rather than get a callback from something
https://stackoverflow.com/questions/38881170/when-should-i-use-eventemitter
If when a certain event happens, we have to deal many type of manipulation for that event’s result, then it is better to use the event emitter pattern.
Instead put all functions inside an event callback, we subscribe all the function to that event, when the event happens, we emit the event!
III. How to use it?
[Good Link]: https://netbasal.com/javascript-the-magic-behind-event-emitter-cce3abcbcef9
[Note]: when pass in the callback function, we use arrow function, which already bind ‘this’ to the function, so that when the function be called, it knows what value it will update
1 |
|
create an emitter util object
subscribe the desired callback function, using
emitter.subscribe(event, function.bind(this))
call
emitter.emit()
when the event happen
IV. Write one!
- object: we need an object (utility object)
- data structure: inside it, we need a data structure to store the
event
and itssubscribers
(callbacks) - methods: all the methods
subscribe(event, callback)
: we need the return value to be anunsubscribe()
, so we won’t result in the memory leak!emit()
1 | class EventEmitter { |
FaceBook interview version
https://gist.github.com/kutyel/7d8f204a347840a6ee7220743957e504
1 | /* |