[feat] dispatch cancelable custom events

pull/7064/head
bluwy 5 years ago
parent 99a04c464d
commit ed8cc0093e

@ -2,7 +2,7 @@ import { custom_event, append, append_hydration, insert, insert_hydration, detac
import { SvelteComponent } from './Component'; import { SvelteComponent } from './Component';
export function dispatch_dev<T=any>(type: string, detail?: T) { export function dispatch_dev<T=any>(type: string, detail?: T) {
document.dispatchEvent(custom_event(type, { version: '__VERSION__', ...detail }, true)); document.dispatchEvent(custom_event(type, { version: '__VERSION__', ...detail }, { bubbles: true }));
} }
export function append_dev(target: Node, node: Node) { export function append_dev(target: Node, node: Node) {

@ -630,9 +630,14 @@ export function toggle_class(element, name, toggle) {
element.classList[toggle ? 'add' : 'remove'](name); element.classList[toggle ? 'add' : 'remove'](name);
} }
export function custom_event<T=any>(type: string, detail?: T, bubbles: boolean = false) { export interface CustomEventOpts {
bubbles?: boolean;
cancelable?: boolean;
}
export function custom_event<T=any>(type: string, detail?: T, opts?: CustomEventOpts) {
const e: CustomEvent<T> = document.createEvent('CustomEvent'); const e: CustomEvent<T> = document.createEvent('CustomEvent');
e.initCustomEvent(type, bubbles, false, detail); e.initCustomEvent(type, opts.bubbles, opts.cancelable, detail);
return e; return e;
} }

@ -1,4 +1,4 @@
import { custom_event } from './dom'; import { custom_event, CustomEventOpts } from './dom';
export let current_component; export let current_component;
@ -32,13 +32,13 @@ export function createEventDispatcher<
>(): <EventKey extends Extract<keyof EventMap, string>>(type: EventKey, detail?: EventMap[EventKey]) => void { >(): <EventKey extends Extract<keyof EventMap, string>>(type: EventKey, detail?: EventMap[EventKey]) => void {
const component = get_current_component(); const component = get_current_component();
return (type: string, detail?: any) => { return (type: string, detail?: any, opts?: CustomEventOpts) => {
const callbacks = component.$$.callbacks[type]; const callbacks = component.$$.callbacks[type];
if (callbacks) { if (callbacks) {
// TODO are there situations where events could be dispatched // TODO are there situations where events could be dispatched
// in a server (non-DOM) environment? // in a server (non-DOM) environment?
const event = custom_event(type, detail); const event = custom_event(type, detail, opts);
callbacks.slice().forEach(fn => { callbacks.slice().forEach(fn => {
fn.call(component, event); fn.call(component, event);
}); });

Loading…
Cancel
Save