Write a function named createPubSub
that returns an object implementing a basic Publish-Subscribe pattern.
The object - let's call it pubSubBroker
- should have the following properties:
publish
- a method used to publish an event. It should accept 2 parameters:
eventId
- a string uniquely identifying the eventeventData
- any data that should be passed to the subscribers of the eventsubscribe
- a method used to subscribe to a certain event. It should accept 2 parameters:
eventId
- a string uniquely identifying the eventcallback(data)
- a function that will be called when the event is published. The function will receive one parameter - the eventData
passed when publishing this specific event.The function should return another function called unsubscribe
that can be used to unsubscribe from this event.
class Person {
name;
pubSubBroker;
unsubscribeFn;
constructor(name, pubSubBroker) {
this.name = name;
this.pubSubBroker = pubSubBroker;
this.unsubscribeFn = this.pubSubBroker.subscribe(
`calling.${this.name}`,
(eventData) => {
this.pickUpPhone(eventData)
}
)
}
pickUpPhone({ caller }) {
console.log(`Hello ${caller}, this is ${this.name}! What's up?`);
}
callSomeone(name) {
console.log(`Let's call ${name}.`);
pubSubBroker.publish(`calling.${name}`, { caller: this.name });
}
closePhone() {
this.unsubscribeFn();
}
}
const pubSubBroker = createPubSub();
const bob = new Person('Bob', pubSubBroker);
const george = new Person('George', pubSubBroker);
const lisa = new Person('Lisa', pubSubBroker);
bob.callSomeone('Lisa');
/**
* Should print:
* > Let's call Lisa.
* > Hello Bob, this is Lisa! What's up?
*/
george.callSomeone('Lisa');
/**
* Should print:
* > Let's call Lisa.
* > Hello George, this is Lisa! What's up?
*/
lisa.callSomeone('Bob');
/**
* Should print:
* > Let's call Bob.
* > Hello Lisa, this is Bob! What's up?
*/