-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(esl-mixin-element): improve observation mechanism of mixin's obs…
…erved attributes
- Loading branch information
Showing
2 changed files
with
50 additions
and
26 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import {ESLMixinRegistry} from './esl-mixin-registry'; | ||
import type {ESLMixinElement, ESLMixinElementInternal} from './esl-mixin-element'; | ||
|
||
let instance: ESLMixinAttributesObserver; | ||
export class ESLMixinAttributesObserver { | ||
protected observer = new MutationObserver( | ||
(records: MutationRecord[]) => records.forEach(this.handleRecord, this) | ||
); | ||
|
||
constructor() { | ||
if (instance) return instance; | ||
// eslint-disable-next-line @typescript-eslint/no-this-alias | ||
instance = this; | ||
} | ||
|
||
protected handleRecord(record: MutationRecord): void { | ||
const name = record.attributeName; | ||
const target = record.target as HTMLElement; | ||
if (!name || !target) return; | ||
const mixins = ESLMixinRegistry.getAll(target) as ESLMixinElementInternal[]; | ||
for (const mixin of mixins) { | ||
const observed = (mixin.constructor as typeof ESLMixinElement).observedAttributes; | ||
if (!observed.includes(record.attributeName)) return; | ||
mixin.attributeChangedCallback(name, record.oldValue, target.getAttribute(name)); | ||
} | ||
} | ||
|
||
public observe(mixin: ESLMixinElement): void { | ||
const {observedAttributes} = mixin.constructor as typeof ESLMixinElement; | ||
if (!observedAttributes.length) return; | ||
this.observer.observe(mixin.$host, { | ||
attributes: true, | ||
attributeFilter: observedAttributes, | ||
attributeOldValue: true | ||
}); | ||
} | ||
|
||
public unobserve(mixin: ESLMixinElement): void { | ||
this.observer.observe(mixin.$host, { | ||
attributes: true, | ||
attributeFilter: [], | ||
attributeOldValue: true | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters