查看: 904|回复: 0

[JavaScript/JQuery] Make a simple custom EventEmitter

发表于 2018-3-17 08:00:01
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 triggerd, walk through the associated listeners/handlers and execute them.

  1. class Emitter {
  2. constructor(){
  3. /**
  4. * keep mapping information。
  5. * e.g.
  6. * {
  7. * 'event1': [fn1, fn2],
  8. * 'event2': [fn3, fn4, fn5]
  9. * }
  10. */
  11. this.handlers = {};
  12. }
  13. }
复制代码
Some details about the methods on - event binding
  1. on(evt, handler) {
  2. this.handlers[evt] = this.handlers[evt] || [];
  3. let hdl = this.handlers[evt];
  4. hdl.push(handler);
  5. return this;
  6. }
复制代码

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
  1. removeListener(evt, handler) {
  2. this.handlers[evt] = this.handlers[evt] || [];
  3. let hdl = this.handlers[evt];
  4. let index = hdl.indexOf(handler);
  5. if(index >= 0) {
  6. hdl.splice(index, 1);
  7. }
  8. return this;
  9. }
复制代码

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.

  1. function f1() {
  2. console.log('hi');
  3. }
  4. function f2() {
  5. console.log('hi');
  6. }
  7. let f3 = f1;
  8. console.log(f1 === f2); //false
  9. console.log(f1 === f3); //true
复制代码
once - binding, but only can be triggerd once
  1. once(evt, handler) {
  2. this.handlers[evt] = this.handlers[evt] || [];
  3. let hdl = this.handlers[evt];
  4. hdl.push(function f(...args){
  5. handler.apply(this, args);
  6. this.removeListener(evt, f);
  7. });
  8. return this;
  9. }
复制代码

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
  1. emit(evt, ...args) {
  2. this.handlers[evt] = this.handlers[evt] || [];
  3. let hdl = this.handlers[evt];
  4. hdl.forEach((it) => {
  5. it.apply(this, args);
  6. });
  7. return this;
  8. }
复制代码

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
  1. eventNames() {
  2. return Object.keys(this.handlers).reduce((arr, evt) => {
  3. if(this.listenerCount(evt)) {
  4. arr.push(evt);
  5. }
  6. return arr;
  7. }, []);
  8. }
复制代码

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.

  1. let server = new Emitter();
  2. let fn = function(){};
  3. server.on('connection', fn);
  4. server.removeListener('connection', fn);
  5. server.handlers.connection; //[]
复制代码

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 many situations where reduce can be useful, such as computing the sum of an array:

  1. function sumWithForEach(arr) { // with forEach
  2. let sum = 0;
  3. arr.forEach(it => {
  4. sum += it;
  5. })
  6. return sum;
  7. }
  8. function sumWithReduce(arr) { // with reduce
  9. return arr.reduce((sum, current) => {
  10. return sum + current;
  11. })
  12. }
复制代码
Reference Async Javascript Notice If 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.


回复

使用道具 举报