参考链接: https://segmentfault.com/q/1010000040034919
回调方式
定义方法
function receiver(type, callback) {document.addEventListener(type, (ev) => {callback(ev);});}
使用
receiver('click', (ev) => {console.log(ev)})
链式调用
方法一
定义
const receiver = (() => {const callbacks = {};return function (type) {const list = callbacks[type];if (!list) {document.addEventListener(type, (ev) => {callbacks[type].forEach(fn => fn(ev));});}return {then(callback) {(callbacks[type] ??= []).push(callback);}};};})();
使用
receiver("click").then(() => console.log("hello"));receiver("click").then(() => console.log("hi"));const click = receiver("click");click.then(() => console.log("aaaaa"));click.then(() => console.log("bbbbbb"));
方法二
可以多个链式调用
定义
function receiver(type) {let callbacks = {fns: [],then: function(cb){this.fns.push(cb)return this}}document.addEventListener(type, function(ev) {let fns = callbacks.fns.slice()for(let i = 0, l = fns.length; i < l; i++){fns[i].call(this, ev)}});return callbacks}
使用
receiver("click").then(() => console.log("hi")).then(()=>console.log(22));
