class Event {
// 监听函数
static on(eventName, callback) {
if (!eventName) {
return
}
if (!this.handles) {
Object.defineProperty(this, "handles", {
value: {}, // 默认值是{}
enumerable: false, // 不可枚举
configurable: true, // 可以delete删除
writable: true // 可以修改
})
}
// 如果对象中没有这个名字,就创建一个数组,之后把名字和方法存在来
if (!this.handles[eventName]) {
this.handles[eventName] = []
}
// 把对应方法push到数组里
this.handles[eventName].push(callback)
}
// 触发函数
static emit(eventName) {
let nameAry = this.handles[eventName]
// 处理对象里存在这个名字的数组,就把数组的方法执行了
if (nameAry instanceof Array) {
for (let i = 0; i < nameAry.length; i++) {
nameAry[i]()
}
}
}
// 解绑函数
static off(eventName) {
let nameAry = this.handles[eventName]
if (nameAry instanceof Array) {
this.handles[eventName] = null
}
}
}
Event.on('oufuhua', function () {
console.log('哈哈哈')
})
Event.on('oufuhua', function () {
console.log('我叫oufuhua')
})
// Event.off('oufuhua')
Event.emit('oufuhua')
网友评论