-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtiny-context.js
54 lines (48 loc) · 1.5 KB
/
tiny-context.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
export class ContextRequestEvent extends Event {
constructor(context, callback, subscribe) {
super('context-request', {
bubbles: true,
composed: true,
});
this.context = context;
this.callback = callback;
this.subscribe = subscribe;
}
}
export class ContextProvider extends EventTarget {
#value;
get value() { return this.#value }
set value(v) { this.#value = v; this.dispatchEvent(new Event('change')); }
#context;
get context() { return this.#context }
constructor(target, context, initialValue = undefined) {
super();
this.#context = context;
this.#value = initialValue;
this.handle = this.handle.bind(this);
if (target) this.attach(target);
}
attach(target) {
target.addEventListener('context-request', this.handle);
}
detach(target) {
target.removeEventListener('context-request', this.handle);
}
/**
* Handle a context-request event
* @param {ContextRequestEvent} e
*/
handle(e) {
if (e.context === this.context) {
if (e.subscribe) {
const unsubscribe = () => this.removeEventListener('change', update);
const update = () => e.callback(this.value, unsubscribe);
this.addEventListener('change', update);
update();
} else {
e.callback(this.value);
}
e.stopPropagation();
}
}
}