在JavaScript中实现发布-订阅模式可以通过以下步骤来完成:
class EventEmitter {
constructor() {
this.events = {};
}
on(eventName, callback) {
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push(callback);
}
emit(eventName, ...args) {
if (!this.events[eventName]) {
return;
}
this.events[eventName].forEach(callback => callback(...args));
}
}
const emitter = new EventEmitter();
function callback1(data) {
console.log('callback1', data);
}
function callback2(data) {
console.log('callback2', data);
}
emitter.on('event1', callback1);
emitter.on('event1', callback2);
emitter.emit('event1', 'hello world');
// 输出:
// callback1 hello world
// callback2 hello world
这样就可以实现发布-订阅模式了。其中,关键词包括事件中心对象、订阅、发布、事件名、回调函数、参数等。