UNPKG

@ideal-postcodes/postcode-lookup

Version:
46 lines (45 loc) 1.67 kB
/** * @module Watch */ import { setup } from "./setup"; import { getScope, getParent, watchChange, toArray, loaded, markLoaded, } from "@ideal-postcodes/jsutil"; const isTrue = () => true; const NOOP = () => { }; const formScope = (anchor) => getParent(anchor, "FORM"); const getAnchors = (config, marker) => { const scope = getScope(config.scope || null); const matches = scope.querySelectorAll(config.anchor || config.context || config.scope); return toArray(matches).filter((e) => !loaded(e, marker)); }; /** * Dynamically apply PostcodeLookup * when relevant html configuration appear * - Exits if page test is fails * - Not binding when context is null or already have controller bound * - Use controller bind to build solution */ export const watch = (config, options = {}) => { const { pageTest = isTrue, onError = NOOP, onBindAttempt = NOOP, onBind = NOOP, anchor, onAnchorFound = NOOP, getScope = formScope, marker = "idpc-pl", } = options; let controller; const bind = () => { try { onBindAttempt(config); getAnchors({ anchor, ...config }, marker).forEach((anchor) => { if (!pageTest()) return; const scope = getScope(anchor); onAnchorFound({ anchor, scope, config }); controller = setup(config); markLoaded(anchor, marker); onBind(controller); }); } catch (error) { onError(error); } }; const { start, stop } = watchChange({ bind }); //start watching changes start(); return { start, stop, controller }; };