Skip to content

Instantly share code, notes, and snippets.

@luan0ap
Last active August 11, 2022 22:17
Show Gist options
  • Save luan0ap/7bb99a159525d2265582baff9b1b6674 to your computer and use it in GitHub Desktop.
Save luan0ap/7bb99a159525d2265582baff9b1b6674 to your computer and use it in GitHub Desktop.
My Observe Pattern implementation using classes
class Observer {
#id
#container
constructor() {
this.#id = 0
this.#container = {}
}
subscribe(topic, f) {
if (!(topic in this.#container)) {
this.#container[topic] = [];
}
this.#container[topic].push({
'id': ++this.#id,
'callback': f
});
return this.#id;
}
unsubscribe(topic, id) {
let subscribers = [];
for (const subscriber of this.#container[topic]) {
if (subscriber.id !== this.#id) {
subscribers.push(subscriber);
}
}
this.#container[topic] = subscribers;
}
publish(topic, data) {
for (const subscriber of this.#container[topic]) {
subscriber.callback(data);
}
}
}
const observe = new Observer()
let subscriptionID1 = observe.subscribe('mouseClicked', (data) => {
console.log('mouseClicked', JSON.stringify(data))
})
let subscriptionID2 = observe.subscribe('mouseHovered', (data) => {
console.log('mouseHovered', JSON.stringify(data))
})
// When we publish an event, all callbacks should
// be called and you will see three logs
observe.publish('mouseClicked', {
"data": "data1"
})
observe.publish('mouseHovered', {
"data": "data2"
})
// We unsubscribe an event
observe.unsubscribe("mouseClicked", subscriptionID1)
// now we have 1 log
observe.publish('mouseClicked', {
"data": "data1"
})
observe.publish('mouseHovered', {
"data": "data2"
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment