Make a simple custom EventEmitter how to name a file to appear professional, customeventemitter
Thoughts
Recently I have been reading the book Async Javascript about JS asynchronicity and JS event is one of the useful solutions to the problem. to get a deeper understanding of how events work, I create a custom EventEmitter which constains most of the working functionalities of Node EventEmitter. the source code is no more than 60 lines.
General ideas
The general ideas is to have an object (this. handlers) to hold the mapping from event name (type: string) to its associated listeners/handlers (type: Array \). when each event is trigadh, walk through the associated listeners/handlers and execute them.
Copy code
Some details about the methodson-event binding
Copy code
We don't check the duplicates when binding the handler for simplicity. that is to say, if you call on for the same function twice, then it will be called twice when the event is triggered. the method returns this to allow for method chaining.
Off-event unbinding
Copy code
Note that here we compare the function reference with strict comparision when unbinding a function. Function in Javascript is compared by their reference, same as how objects comparision works.
Copy code
Once-binding, but only can be trigadh once
Copy code
It works similarly with on method. But we need to wrap the handler with another function such that we can remove the binding once the handler is executed to achieve triggered only once.
Emit-trigger event
Copy code
When an event is triggered, find all its associated handlers (I. e. this. handlers [evt]) and execute them.
EventNames-get the list of registered events which has active (I. e. not-empty) handlers
Copy code
Here we don't simply return all the keys of the this. handlers, as some events can be binded with some handlers and then remove them afterwards. in the case, the event name exists as a valid key in this. handlers but without active handlers. e. g.
Copy code
Therefore, we need to filter out the events with empty hanlders. here we use Array. prototype. reduce to make the code a little bit cleaner. there are using situations where reduce can be useful, such as computing the sum of an array:
Copy code
ReferenceAsync JavascriptNoticeIf you benefit from this Repo, Please "Star" to Support. If you want to follow the latest news/articles for the series of reading notes, Please "Watch" to Subscribe.