自定义事件
原题目:
<script>
function Event() {
this.event = [] // 用于存储注册的事件
}
// 注册事件
Event.prototype.on = function(eventType, callBacks) {
this.event.push({
eventType,
callBacks,
done: false, //控制是否执行
once: false // 控制只执行一次的事件
})
}
// 解除事件
Event.prototype.off = function(eventType, callBacks) {
this.event.map((item, i) => {
if(item.eventType === eventType && item.callBacks === callBacks) {
this.event.splice(i, 1)
}
})
}
// 触发事件
Event.prototype.emit = function(eventType) {
this.event.forEach(item => {
if(item.eventType === eventType) {
if(!item.done){
item.callBacks()
if(item.once) { // 如果once是true,就让done变为true,之后就不会在执行这一个事件了
item.done = true
}
}
}
})
}
// 注册只执行一次的事件
Event.prototype.once = function(eventType, callBacks) {
this.event.push({
eventType,
callBacks,
done:false,
once: true
})
}
function fn1() {console.log(1)}
function fn2() {console.log(2)}
function fn3() {console.log(3)}
const myEvent = new Event()
myEvent.on('click', fn1)
myEvent.on('click', fn2)
myEvent.once('click', fn3) // 只执行一次
myEvent.emit('click')// 1, 2, 3
myEvent.off('click', fn1) // 解除
myEvent.emit('click') // 2
myEvent.on('tap', fn1)
myEvent.emit('tap') // 1
console.log(myEvent.event)
</script>

浙公网安备 33010602011771号