Events function () { // place all monitor events added to the this ._events = {} } Events.prototype = { ON: function (name, the Fn, ... argOrg) { // will pass parameter validation IF (name |! ! | Fn) { the throw new new Error ( `[Events TypeError] the Failed to Execute ' Events ' ON ' $ {name} ' : 2 arguments required `) return } // prevent repeated additions of the same monitor the let FNS = the this ._events [ name] || [] IF(fns.find(item=> item.fnOrg===fn)){ return; } this._events[name] = fns.concat({ fn: arg => fn.apply(null, [...argOrg, ...arg]), fnOrg:fn }) }, once: function (name, fn, ...argOrg) { const onFn = (...arg) =>{ fn.apply(null, arg) this.off(name, onFn) } this.on(name, onFn, ...argOrg) }, emit: function (name, ...arg) { (this._events[name]||[]).forEach(item =>{ item.fn (Arg) }) }, OFF: function (name, the Fn) { // without parameters: clear out all listeners IF ! ( Arguments.length) { the this ._events = Object.create ( null ) } // one argument: the event is cleared name all listeners IF (== The arguments.length . 1 ) { Delete the this ._events [name] } the let FNS = the this ._events [name]; IF (! fns.length FNS ||!) return ; the this ._events [name ] = (FNS || []) filter (Item =>. { return item.fnOrg ==! Fn }); } } // 调用demo const event = new Events(); const fn1 = (...args)=>console.log('I want sleep1',...args) const fn2 = (...args)=>console.log('I want sleep2',...args) // part1: 添加多次监听 event.on('sleep', fn1, 1, 2, 3); event.on('sleep', fn2, 4, 5, 6); Event .emit ( ' SLEEP ' , . 7 , . 8 , . 9 ); // output // the I want SLEEP1. 1 2. 5. 4. 3. 6 // the I want sleep2. 1 2. 5. 4. 3. 6 // Part2: Once triggered only listens primary Event .once ( ' SLEEP1 ' , Fn1, . 11 , 12 is ); Event .emit ( ' SLEEP1 ' , 13 is ); Event .emit ( ' SLEEP1 ' , 13 is ); // output //SLEEP1 want. 11 12 is 13 is the I // Part3: Repeat listen "same callback" Invalid (except anonymous function) Event .on ( ' sleep2 ' , Fn2, 22 is ); Event .on ( ' sleep2 ' , Fn2, 23 is ); Event . EMIT ( ' sleep2 ' , 25 ); // output // the I want sleep2 22 is 25 // Part3: Clear listener event .off ( ' sleep2 ' , Fn2); event .off ( ' SLEEP1 ' ); // clear the event all listeners Event .off (); // Clear All Event .emit ( ' sleep2 ' , 25 ); // output // No