-
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
lifecycle.ts
70 lines (55 loc) · 1.83 KB
/
lifecycle.ts
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
import { custom_event } from './dom';
export let current_component;
export function set_current_component(component) {
current_component = component;
}
export function get_current_component() {
if (!current_component) throw new Error('Function called outside component initialization');
return current_component;
}
export function beforeUpdate(fn: () => any) {
get_current_component().$$.before_update.push(fn);
}
export function onMount(fn: () => any) {
get_current_component().$$.on_mount.push(fn);
}
export function afterUpdate(fn: () => any) {
get_current_component().$$.after_update.push(fn);
}
export function onDestroy(fn: () => any) {
get_current_component().$$.on_destroy.push(fn);
}
export function createEventDispatcher<
EventMap extends {} = any
>(): <EventKey extends Extract<keyof EventMap, string>>(type: EventKey, detail?: EventMap[EventKey]) => void {
const component = get_current_component();
return (type: string, detail?: any) => {
const callbacks = component.$$.callbacks[type];
if (callbacks) {
// TODO are there situations where events could be dispatched
// in a server (non-DOM) environment?
const event = custom_event(type, detail);
callbacks.slice().forEach(fn => {
fn.call(component, event);
});
}
};
}
export function setContext<T>(key, context: T) {
get_current_component().$$.context.set(key, context);
}
export function getContext<T>(key): T {
return get_current_component().$$.context.get(key);
}
export function hasContext(key): boolean {
return get_current_component().$$.context.has(key);
}
// TODO figure out if we still want to support
// shorthand events, or if we want to implement
// a real bubbling mechanism
export function bubble(component, event) {
const callbacks = component.$$.callbacks[event.type];
if (callbacks) {
callbacks.slice().forEach(fn => fn(event));
}
}