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 ideasThe 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
class Emitter { constructor(){ /** * keep mapping information。 * e.g. * { * "event1": [fn1, fn2], * "event2": [fn3, fn4, fn5] * } */ this.handlers = {}; } }Some details about the methods on - event binding
on(evt, handler) { this.handlers[evt] = this.handlers[evt] || []; let hdl = this.handlers[evt]; hdl.push(handler); return this; }
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 unbindingremoveListener(evt, handler) { this.handlers[evt] = this.handlers[evt] || []; let hdl = this.handlers[evt]; let index = hdl.indexOf(handler); if(index >= 0) { hdl.splice(index, 1); } return this; }
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.
function f1() { console.log("hi"); } function f2() { console.log("hi"); } let f3 = f1; console.log(f1 === f2); //false console.log(f1 === f3); //trueonce - binding, but only can be triggerd once
once(evt, handler) { this.handlers[evt] = this.handlers[evt] || []; let hdl = this.handlers[evt]; hdl.push(function f(...args){ handler.apply(this, args); this.removeListener(evt, f); }); return this; }
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 eventemit(evt, ...args) { this.handlers[evt] = this.handlers[evt] || []; let hdl = this.handlers[evt]; hdl.forEach((it) => { it.apply(this, args); }); return this; }
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) handlerseventNames() { return Object.keys(this.handlers).reduce((arr, evt) => { if(this.listenerCount(evt)) { arr.push(evt); } return arr; }, []); }
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.
let server = new Emitter(); let fn = function(){}; server.on("connection", fn); server.removeListener("connection", fn); 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:
function sumWithForEach(arr) { // with forEach let sum = 0; arr.forEach(it => { sum += it; }) return sum; } function sumWithReduce(arr) { // with reduce return arr.reduce((sum, current) => { return sum + current; }) }Reference
Async Javascript
NoticeIf 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.
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/93310.html
摘要:的介绍一般是这样在中,类是随内核一起发布的核心库。库为带来了一种存储原始数据的方法,可以让处理二进制数据,每当需要在中处理操作中移动的数据时,就有可能使用库。这样传递数据会更快。 零、开始之前 1、 首先解释一下node.js是什么? 2、node.js和javascript有什么不同? 1)因为javascript主要是用在browser,而node.js是在server或者你的电脑...
MSCI 720 Monday Jan 9 Lec 3/36 Syllabus TREC Agreement Summary-Review Architecture TREC text format Tokenization Tutorials will be used to tutor and help students to complete the assignments Outcome...
摘要:注解的元数据选择器页面渲染时,组件匹配的选择器使用方式采用标签的方式。当然必要的,在需要用到的的模块中引入引入的指令,放在声明里面引入的模块引导应用的根组件关于的元数据还未完全,所以后面会继续完善。 angular学习笔记之组件篇 showImg(https://i.imgur.com/NQG0KG1.png); 1注解 1.1组件注解 @Component注解,对组件进行配置。 1....
摘要:注解的元数据选择器页面渲染时,组件匹配的选择器使用方式采用标签的方式。当然必要的,在需要用到的的模块中引入引入的指令,放在声明里面引入的模块引导应用的根组件关于的元数据还未完全,所以后面会继续完善。 angular学习笔记之组件篇 showImg(https://i.imgur.com/NQG0KG1.png); 1注解 1.1组件注解 @Component注解,对组件进行配置。 1....
阅读 924·2019-08-30 14:24
阅读 956·2019-08-30 14:13
阅读 1764·2019-08-29 17:21
阅读 2560·2019-08-29 13:44
阅读 1614·2019-08-29 11:04
阅读 413·2019-08-26 10:44
阅读 2529·2019-08-23 14:04
阅读 850·2019-08-23 12:08