This lesson is only accessible in the paid version of the course.
Get access to all lessons 💫 price: 34.99$
Do you speak JavaScript?
In this video, we will be learning about the Publisher/Subscriber design pattern in JavaScript and how it can be used to decouple objects and improve the overall design of your application.
The publisher/subscriber pattern, also known as the observer pattern, is a software design pattern that enables objects to subscribe and receive notifications from other objects in a decoupled manner. In this pattern, the publisher object dispatches an event, and the subscriber objects receive and act upon that event. This pattern is commonly used in event-driven architectures, where objects react to specific events in the system. Here's an example:
const Bus = {
_listeners: {},
addListener(channel, listener) {
if (!this._listeners[channel]) {
this._listeners[channel] = [];
}
this._listeners[channel].push(listener);
return () => {
this._listeners[channel] =
this._listeners[channel].filter(l => {
return l !== listener;
})
}
},
dispatch(channel, event) {
if (this._listeners[channel]) {
this._listeners[channel].forEach(l => {
l(event);
})
}
}
}
const unsub = Bus.addListener('YYY', (event) => {
console.log('a', event.name);
});
Bus.addListener('XXX', (event) => {
console.log('b', event.name);
});
Bus.dispatch('XXX', { name: 'foobar' });
unsub();
Bus.dispatch('XXX', { name: 'hello' });
Practice is the fastest way to learn knowledge permanently. I have prepared a small task for you related to the lesson.
Materials related to the lesson:
→ Files associated with the lesson