-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (64 loc) · 1.94 KB
/
index.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
function createCounter(initialCount) {
let observers = [];
let count = initialCount;
function subscribe(func) {
observers.push(func);
return unsubscribe;
}
function get() {
observers.forEach((observer) => observer(count));
return count;
}
function set(newCount) {
count = newCount;
observers.forEach((observer) => observer(count));
return count;
}
function unsubscribe(func) {
observers = observers.filter((observer) => observer !== func);
}
return {
subscribe,
get,
set,
unsubscribe,
};
}
let count = 0;
const counter = createCounter(count);
// The subscription, notification and un-subscription can happen inside the
// scope of the click handler or in the global scope, depending on other
// events, however take care of un-subscription on unmount / destroy, or
// i.e. when navigating to another component / page.
function logger(data) {
console.log("current count : ", data);
}
counter.subscribe(logger);
// this logs the value a first time
counter.set(123456789);
// this logs the value a second time
counter.get();
const countElement = document.getElementById("count");
// this will update the DOM
// this logs the value a third time
countElement.innerHTML = counter.get();
// const increment = document.getElementById("increment");
increment.addEventListener("click", function (event) {
// get current count - optional here since count is set external
// the click event also logs the current value, the fourth time in sequence
count = counter.get();
// increment count
count = count + 1;
// set new count
// this logs the new value
countElement.innerHTML = counter.set(count);
// as an alternative the subscription, notification and un-subscription
// can happen inside the scope of the click handler
/*
counter.subscribe(logger);
count = counter.get();
count = count + 1;
countElement.innerHTML = counter.set(count);
counter.unsubscribe(logger);
*/
});