Open david2tdw opened 4 years ago
一个简单的Event bus (观察者模式)
观察者模式另一个简单实现:
const createEventBus = () => ({
bus: Object.create(null),
$emit(event, data) {
(this.bus[event] || []).forEach(handler => handler(data));
},
$on(event, handler) {
// event is not exist
if (!this.bus[event]) {
this.bus[event] = [];
}
this.bus[event].push(handler);
},
$off(event, handler) {
const index = (this.bus[event] || []).findIndex(h => h === handler);
if (index > -1) {
this.bus[event].splice(index, 1);
}
}
});
var bus = createEventBus();
bus.$on('aron', h => {
console.log(`show ${h}`);
});
bus.$on('aron', h => {
console.log(`save ${h}`);
});
bus.$emit('aron', 'tdw');
观察者模式,其实就是为了实现松耦合(loosely coupled)。 发布订阅模式里,发布者和订阅者,不是松耦合,而是完全解耦的。通过消息队列交流。