@surface/custom-element
Version:
Provides support of directives and data binding on custom elements.
31 lines (30 loc) • 1.32 kB
JavaScript
import { tryEvaluateExpressionByTraceable, tryEvaluateKeyExpressionByTraceable, tryObserveByObservable, tryObserveKeyByObservable, } from "../common.js";
export default class Directive {
constructor(context) {
this.context = context;
this.onBeforeBind?.();
this.keySubscription = tryObserveKeyByObservable(this.context.scope, this.context.descriptor, this.keyNotify.bind(this), true);
this.subscription = tryObserveByObservable(this.context.scope, this.context.descriptor, this.valueNotify.bind(this), true);
this.keyNotify();
this.valueNotify();
this.onAfterBind?.();
}
keyNotify() {
const oldKey = this.key;
const newKey = `${tryEvaluateKeyExpressionByTraceable(this.context.scope, this.context.descriptor)}`;
this.key = newKey;
this.onKeyChange?.(newKey, oldKey);
}
valueNotify() {
const oldValue = this.value;
const newValue = tryEvaluateExpressionByTraceable(this.context.scope, this.context.descriptor);
this.value = newValue;
this.onValueChange?.(newValue, oldValue);
}
dispose() {
this.onBeforeUnbind?.();
this.keySubscription.unsubscribe();
this.subscription.unsubscribe();
this.onAfterUnbind?.();
}
}