All files / src/internal/client/dom/elements/bindings shared.js

100% Statements 55/55
100% Branches 8/8
100% Functions 3/3
100% Lines 53/53

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 542x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 14x 14x 14x 14x 14x 20x 20x 14x 14x 14x 20x 20x 14x 14x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 751x 751x 751x 751x 327x 327x 327x 6x 6x 327x 751x 424x 424x 424x 751x 751x 751x  
import { teardown } from '../../../reactivity/effects.js';
import { add_form_reset_listener } from '../misc.js';
 
/**
 * Fires the handler once immediately (unless corresponding arg is set to `false`),
 * then listens to the given events until the render effect context is destroyed
 * @param {EventTarget} target
 * @param {Array<string>} events
 * @param {(event?: Event) => void} handler
 * @param {any} call_handler_immediately
 */
export function listen(target, events, handler, call_handler_immediately = true) {
	if (call_handler_immediately) {
		handler();
	}
 
	for (var name of events) {
		target.addEventListener(name, handler);
	}
 
	teardown(() => {
		for (var name of events) {
			target.removeEventListener(name, handler);
		}
	});
}
 
/**
 * Listen to the given event, and then instantiate a global form reset listener if not already done,
 * to notify all bindings when the form is reset
 * @param {HTMLElement} element
 * @param {string} event
 * @param {() => void} handler
 * @param {() => void} [on_reset]
 */
export function listen_to_event_and_reset_event(element, event, handler, on_reset = handler) {
	element.addEventListener(event, handler);
	// @ts-expect-error
	const prev = element.__on_r;
	if (prev) {
		// special case for checkbox that can have multiple binds (group & checked)
		// @ts-expect-error
		element.__on_r = () => {
			prev();
			on_reset();
		};
	} else {
		// @ts-expect-error
		element.__on_r = on_reset;
	}
 
	add_form_reset_listener();
}