forked from sveltejs/svelte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlifecycle.js
64 lines (50 loc) · 1.52 KB
/
lifecycle.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
import { custom_event } from './dom';
export let current_component;
export function set_current_component(component) {
current_component = component;
}
function get_current_component() {
if (!current_component) throw new Error(`Function called outside component initialization`);
return current_component;
}
export function beforeUpdate(fn) {
get_current_component().$$.before_render.push(fn);
}
export function onMount(fn) {
get_current_component().$$.on_mount.push(fn);
}
export function afterUpdate(fn) {
get_current_component().$$.after_render.push(fn);
}
export function onDestroy(fn) {
get_current_component().$$.on_destroy.push(fn);
}
export function createEventDispatcher() {
const component = current_component;
return (type, detail) => {
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(key, context) {
get_current_component().$$.context.set(key, context);
}
export function getContext(key) {
return get_current_component().$$.context.get(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));
}
}