JS 实现简单的发布订阅模式
// 发布订阅模式
class EventEmitter {
constructor() {
this.listen = {};
}
on(name, callback) {
this.listen[name]
? this.listen[name].push(callback)
: (this.listen[name] = [callback]);
}
off(name, callback) {
if (callback) {
this.listen[name] = this.listen[name].filter(
(params) => params != callback
);
} else {
this.listen[name] = [];
}
}
emit(name, params) {
this.listen[name] && this.listen[name].map((callback) => callback(params));
}
}
测试一下
let EventBus = new EventEmitter();
EventBus.on('message', (params) => {
console.log(params);
});
EventBus.on('message', (params) => {
console.log(params + 1);
});
EventBus.emit('message', 123);
EventBus.emit('message', 456);
EventBus.off('message');
EventBus.emit('message', 789);
输出
123
124
456
457