This repository has been archived by the owner on Nov 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
/
observer-function.js
54 lines (46 loc) · 2.07 KB
/
observer-function.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Define a constructor function for the Subject object
function ButtonSubject() {
this.observersList = []; // Array to hold observer functions
}
// Extend the prototype of the ButtonSubject object with methods for subscribing, unsubscribing, and notifing observers
ButtonSubject.prototype = {
// Method to subscribe an observer
subscribe: function (observer) {
this.observersList.push(observer);
},
// Method to unsubscribe an observer
unsubscribe: function (observerToRemove) {
// Remove the observerToRemove from the array by finding its index
const index = this.observersList.indexOf(observerToRemove);
if (index !== -1) {
this.observersList.splice(index, 1);
}
},
// Method to notify all observers
notify: function (buttonId) {
// Call each observer function based on the button clicked
for (const observer of this.observersList) {
observer(buttonId);
}
},
};
// Instantiate a new ButtonSubject object
const buttonSubject = new ButtonSubject();
// Function to handle button click events and notify observers
function sendButtonClickNotif(event) {
buttonSubject.notify(event.target.id);
}
// Subscribe the observer function to the buttonSubject
buttonSubject.subscribe(function (buttonId) {
const message = `Observer of ${buttonId} has been notified\n`;
document.getElementById("output").textContent = message;
});
// Attach event listeners to the buttons for click events
document
.getElementById("button1")
.addEventListener("click", sendButtonClickNotif);
document
.getElementById("button2")
.addEventListener("click", sendButtonClickNotif);
// Coded with Javascript Design Patterns #5 - Observer Pattern https://www.youtube.com/watch?v=45TeJEmcqk8
// Modified the code as inspired by https://javascriptpatterns.vercel.app/patterns/design-patterns/observer-pattern