/
lifecycle.ts
86 lines (68 loc) · 2.18 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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 interface DispatchOptions {
cancelable?: boolean;
}
export function createEventDispatcher<EventMap extends {} = any>(): <
EventKey extends Extract<keyof EventMap, string>
>(
type: EventKey,
detail?: EventMap[EventKey],
options?: DispatchOptions
) => boolean {
const component = get_current_component();
return (type: string, detail?: any, { cancelable = false } = {}): boolean => {
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, { cancelable });
callbacks.slice().forEach(fn => {
fn.call(component, event);
});
return !event.defaultPrevented;
}
return true;
};
}
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 getAllContexts<T extends Map<any, any> = Map<any, any>>(): T {
return get_current_component().$$.context;
}
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) {
// @ts-ignore
callbacks.slice().forEach(fn => fn.call(this, event));
}
}