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

100% Statements 57/57
100% Branches 9/9
100% Functions 3/3
100% Lines 55/55

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 54 55 562x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 12x 12x 12x 12x 12x 16x 16x 12x 12x 12x 12x 16x 16x 12x 12x 12x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 718x 718x 718x 718x 313x 313x 313x 6x 6x 313x 718x 405x 405x 405x 718x 718x 718x  
import { render_effect } 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 {Element | Window} target
 * @param {Array<string>} events
 * @param {() => 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);
	}
 
	render_effect(() => {
		return () => {
			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();
}