@ideal-postcodes/postcode-lookup
Version:
UK Postcode Lookup plugin from Ideal Postcodes
50 lines (49 loc) • 1.83 kB
JavaScript
/**
* @module Watch
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.watch = void 0;
const setup_1 = require("./setup");
const jsutil_1 = require("@ideal-postcodes/jsutil");
const isTrue = () => true;
const NOOP = () => { };
const formScope = (anchor) => (0, jsutil_1.getParent)(anchor, "FORM");
const getAnchors = (config, marker) => {
const scope = (0, jsutil_1.getScope)(config.scope || null);
const matches = scope.querySelectorAll(config.anchor || config.context || config.scope);
return (0, jsutil_1.toArray)(matches).filter((e) => !(0, jsutil_1.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
*/
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 = (0, setup_1.setup)(config);
(0, jsutil_1.markLoaded)(anchor, marker);
onBind(controller);
});
}
catch (error) {
onError(error);
}
};
const { start, stop } = (0, jsutil_1.watchChange)({ bind });
//start watching changes
start();
return { start, stop, controller };
};
exports.watch = watch;
;