<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>简单发布订阅</title>
</head>
<body>
<script>
let event = {
list: {},
on(key, fn) {
if (!this.list[key]) {
this.list[key] = []
}
this.list[key].push(fn)
},
emit() {
let key = [].shift.call(arguments),
fns = this.list[key];
if (!fns || fns.length === 0) {
return false
}
fns.forEach(fn => {
fn.apply(this, arguments)
})
},
remove(key, fn) {
console.log('取消订阅事件');
let fns = this.list[key];
if (!fns) return false;
if (!fn) {
fns && (fns.length = 0);
} else {
fns.forEach((cb, i) => {
if (cb == fn) {
fns.splice(i, 1)
}
})
}
}
}
function cat() {
console.log('我是一只猫');
}
function dog() {
console.log('我是旺财');
}
event.on('pet', data => {
console.log(data);
});
event.on('pet', cat);
event.on('pet', dog);
event.remove('pet', dog);
event.emit('pet', ['波斯猫1', '琵琶狗1'])
</script>
</body>
</html>
emit (type, ...params) {
if (!(type in this.handlers)) {
return new Error('未注册该事件')
}
this.handlers[type].forEach(handler => {
handler(...params)
})
}