@surface/custom-element
Version:
Provides support of directives and data binding on custom elements.
34 lines (33 loc) • 1.18 kB
JavaScript
function queryFactory(fn, nocache) {
return (target, propertyKey) => {
const PRIVATE_KEY = Symbol(propertyKey.toString());
Object.defineProperty(target, propertyKey, {
configurable: true,
get() {
if (!this.shadowRoot) {
throw Error("Can't query a closed shadow root");
}
if (!!nocache || Object.is(this[PRIVATE_KEY], undefined)) {
this[PRIVATE_KEY] = fn(this.shadowRoot);
}
return this[PRIVATE_KEY];
},
});
};
}
/**
* Injects lazy queried element.
* @param selector Selector used to element query.
* @param nocache Specifies whether the element should be cached.
*/
export function query(selector, nocache) {
return queryFactory(x => x.querySelector(selector), nocache);
}
/**
* Injects all queried element.
* @param selector Selector used to elements query.
* @param nocache Specifies whether the elements should be cached.
*/
export function queryAll(selector, nocache) {
return queryFactory(x => x.querySelectorAll(selector), nocache);
}