Modify event forwarding to allow opting out

For events which we dispatch ourselves, we can use this to skip the forwarding. Otherwise the listeners don't fire.

svelte-material-ui uses a custom dispatch to get around this issue, I think.
This commit is contained in:
Ryan Gossiaux
2021-12-20 17:44:20 -08:00
parent 31ac0934b0
commit 5783a20cdc

View File

@@ -10,7 +10,7 @@ import {
const MODIFIER_DIVIDER = "!"; const MODIFIER_DIVIDER = "!";
const modifierRegex = new RegExp(`^[^${MODIFIER_DIVIDER}]+(?:${MODIFIER_DIVIDER}(?:preventDefault|stopPropagation|passive|nonpassive|capture|once|self))+$`); const modifierRegex = new RegExp(`^[^${MODIFIER_DIVIDER}]+(?:${MODIFIER_DIVIDER}(?:preventDefault|stopPropagation|passive|nonpassive|capture|once|self))+$`);
export function forwardEventsBuilder(component: SvelteComponent) { export function forwardEventsBuilder(component: SvelteComponent, except: string[] = []) {
// This is our pseudo $on function. It is defined on component mount. // This is our pseudo $on function. It is defined on component mount.
let $on: (eventType: string, callback: (event: any) => void) => () => void; let $on: (eventType: string, callback: (event: any) => void) => () => void;
// This is a list of events bound before mount. // This is a list of events bound before mount.
@@ -20,6 +20,16 @@ export function forwardEventsBuilder(component: SvelteComponent) {
component.$on = (fullEventType: string, callback: (event: any) => void) => { component.$on = (fullEventType: string, callback: (event: any) => void) => {
let eventType = fullEventType; let eventType = fullEventType;
let destructor = () => { }; let destructor = () => { };
if (except.includes(eventType)) {
// Bail out of the event forwarding and run the normal Svelte $on() code
const callbacks = (component.$$.callbacks[eventType] || (component.$$.callbacks[eventType] = []));
callbacks.push(callback);
return () => {
const index = callbacks.indexOf(callback);
if (index !== -1)
callbacks.splice(index, 1);
};
}
if ($on) { if ($on) {
// The event was bound programmatically. // The event was bound programmatically.
destructor = $on(eventType, callback); destructor = $on(eventType, callback);