-
Notifications
You must be signed in to change notification settings - Fork 4
/
sync.js
44 lines (38 loc) · 1.55 KB
/
sync.js
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
import {directive} from "lit-html/lib/directive.js";
import {eventNameForProperty} from "./notify.js";
// eslint-disable-next-line valid-jsdoc
/**
* Mixin that provides a lit-html directive to sync a property to a child property
*
* @template TBase
* @param {Constructor<TBase>} baseElement
*/
export const LitSync = (baseElement) => class extends baseElement {
constructor() {
super();
/**
* lit-html directive to sync a property to a child property
*
* @param {string} property - The property name
* @param {string} [eventName] - Optional event name to sync on, defaults to propertyname-changed
*/
this.sync = directive((property, eventName) => (part) => {
part.setValue(this[property]);
// mark the part so the listener is only attached once
if (!part.syncInitialized) {
part.syncInitialized = true;
const notifyingElement = part.committer.element;
const notifyingProperty = part.committer.name;
const notifyingEvent = eventName || eventNameForProperty(notifyingProperty);
notifyingElement.addEventListener(notifyingEvent, (e) => {
const oldValue = this[property];
this[property] = e.detail.value;
if (this.__lookupSetter__(property) === undefined) {
this.updated(new Map([[property, oldValue]]));
}
});
}
});
}
}
export default LitSync;