@aurelia-mdc-web/select
Version:
Wrapper for Material Components Web Select
96 lines • 3.49 kB
JavaScript
import { __decorate, __metadata } from "tslib";
import { DOM } from 'aurelia-pal';
import { subscriberCollection, EventSubscriber } from 'aurelia-binding';
/**
* @hidden
* The observer only passes values to the element if options has been set at least once.
* When the options are set for the first time the observer passes the value to the element.
* Subsequent options changes pull the value from the element.
* Subsequent value changes are passed to the element.
*/
let MdcSelectValueObserver = class MdcSelectValueObserver {
constructor(element, handler) {
this.handler = handler;
this.element = element;
}
setElementValue(skipNotify = false) {
// do not pass the value to the element if options has never been set
// the value will be passed on when options do arrive
if (this.optionsWereSet) {
this.element.au.controller.viewModel.setValue(this.value, skipNotify);
}
}
getValue() {
return this.value;
}
setValue(newValue) {
if (this.value === newValue) {
return;
}
// assign and sync element.
this.oldValue = this.value;
this.value = newValue;
this.setElementValue();
this.notify();
}
synchronizeValue() {
const value = this.element.value;
if (value !== this.value) {
this.oldValue = this.value;
this.value = value;
this.notify();
}
}
notify() {
const oldValue = this.oldValue;
const newValue = this.value;
this.callSubscribers(newValue, oldValue);
}
handleEvent() {
this.synchronizeValue();
}
subscribe(context, callable) {
if (!this.hasSubscribers()) {
this.handler.subscribe(this.element, this);
}
this.addSubscriber(context, callable);
}
unsubscribe(context, callable) {
if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) {
this.handler.dispose();
}
}
bind() {
const menu = this.element.querySelector('.mdc-menu');
this.optionsWereSet = !!menu.querySelector('mdc-list-item');
this.domObserver = DOM.createMutationObserver((records) => {
if (records.find(x => x.type === 'childList'
&& (Array.from(x.addedNodes).find(y => y.tagName === 'MDC-LIST-ITEM')
|| Array.from(x.removedNodes).find(y => y.tagName === 'MDC-LIST-ITEM')))) {
if (this.optionsWereSet) {
if (this.element.value != this.value) {
this.element.value = undefined;
}
}
else {
this.optionsWereSet = true;
// if options are set for the first time pass the current value to the element
this.setElementValue(true);
}
this.synchronizeValue();
}
});
this.domObserver.observe(menu, { childList: true, subtree: true, characterData: true });
}
unbind() {
this.optionsWereSet = false;
this.domObserver?.disconnect();
this.domObserver = null;
}
};
MdcSelectValueObserver = __decorate([
subscriberCollection(),
__metadata("design:paramtypes", [Element, EventSubscriber])
], MdcSelectValueObserver);
export { MdcSelectValueObserver };
//# sourceMappingURL=mdc-select-value-observer.js.map