fix: simplify MutationSensitiveArray listener system

This commit is contained in:
shirakaba
2022-12-17 22:46:07 +09:00
parent 95f9c44441
commit 217cd78114
2 changed files with 9 additions and 29 deletions

View File

@@ -8,32 +8,11 @@
* its entire purpose is to be used for performance-sensitive tasks.
*/
export class MutationSensitiveArray<T> extends Array<T> {
private readonly listeners: (() => void)[] = [];
once(listener: () => void): void {
const wrapper = () => {
listener();
this.removeListener(wrapper);
};
this.addListener(wrapper);
}
addListener(listener: () => void): void {
if (!this.listeners.includes(listener)) {
this.listeners.push(listener);
}
}
removeListener(listener: () => void): void {
const index = this.listeners.indexOf(listener);
if (index > -1) {
this.listeners.splice(index, 1);
}
}
onMutation: (() => void) | null = null;
private invalidate(): void {
for (const listener of this.listeners) {
listener();
if (this.onMutation) {
this.onMutation();
}
}