class People {
constructor(name) {
this.name = name
}
events = {}
handleArgs(...callback) {
let args = [...new Set([...callback])].slice(1)
args = args.filter((i) => typeof i === "function")
return args
}
on(type) {
let args = this.handleArgs.apply(null, [...arguments])
this.events[type] ? this.events[type].push(...args) : (this.events[type] = args)
}
emit(type, ...params) {
if (!this.events[type] || !this.events[type].length) throw new Error("没有此类型事件")
this.events[type].forEach((item) => item.apply(this, [...params]))
}
off(type) {
if (!this.events[type] || !this.events[type].length) throw new Error("没有此类型事件")
let args = this.handleArgs.apply(null, [...arguments])
args.forEach((item) => {
let idx = this.events[type].indexOf(item)
if (idx > -1) {
this.events[type].splice(idx, 1)
} else {
throw new Error("没有与此类型对应的函数,请检查需要解绑的函数名")
}
})
}
sayHi() {
console.log(`Hi, I am ${this.name}`)
}
}
const say1 = (greeting) => {
console.log(`${greeting}, nice meeting you.`)
}
const say2 = (greeting) => {
console.log(`${greeting}, nice meeting you, too.`)
}
const jerry = new People("Jerry")
jerry.sayHi()
jerry.on("greeting", say1)
jerry.on("greeting", say2)
jerry.emit("greeting", "Hi")
jerry.off("greeting", say1)
jerry.emit("greeting", "Hi")