知识点
- 观察者模式的概念和实现
class
的使用
题目
完成EventEmitter
模块,它是一个类,它的实例具有以下几个方法:on
、emit
、off
:
on(eventName, func)
:监听eventName
事件,事件触发的时候调用func
函数。emit(eventName, arg1, arg2, arg3...)
:触发eventName
事件,并且把参数arg1
,arg2
,arg3
… 传给事件处理函数。off(eventName, func)
:停止监听某个事件。
使用例子:
const emitter = new EventEmitter()
const sayHi = (name) => console.log(`Hello ${name}`)
const sayHi2 = (name) => console.log(`Good night, ${name}`)
emitter.on('hi', sayHi)
emitter.on('hi', sayHi2)
emitter.emit('hi', 'ScriptOJ')
// => Hello ScriptOJ
//