Skip to content

Commit 217cd78

Browse files
committed
fix: simplify MutationSensitiveArray listener system
1 parent 95f9c44 commit 217cd78

File tree

2 files changed

+9
-29
lines changed

2 files changed

+9
-29
lines changed

packages/core/data/dom-events/dom-event.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -353,16 +353,17 @@ export class DOMEvent implements Event {
353353

354354
// Set a listener to clone the array just before any mutations.
355355
let listenersLazyCopy: ListenerEntry[] = listenersLive;
356-
const doLazyCopy = () => {
356+
listenersLive.onMutation = () => (mutation: string, payload?: unknown) => {
357+
console.log(`handleEvent "${data.eventName}": doLazyCopy due to "${mutation}"`, payload);
357358
// Cloning the array via spread syntax is up to 180 nanoseconds
358359
// faster per run than using Array.prototype.slice().
359360
listenersLazyCopy = [...listenersLive];
361+
listenersLive.onMutation = null;
360362
};
361-
listenersLive.once(doLazyCopy);
362363

363-
// Make sure we remove the listener before we exit the function,
364-
// otherwise we may wastefully clone the array.
365-
const cleanup = () => listenersLive.removeListener(doLazyCopy);
364+
// Make sure we clear the callback before we exit the function,
365+
// otherwise we may wastefully clone the array on future mutations.
366+
const cleanup = () => (listenersLive.onMutation = null);
366367

367368
for (let i = listenersLazyCopy.length - 1; i >= 0; i--) {
368369
const listener = listenersLazyCopy[i];

packages/core/data/mutation-sensitive-array/index.ts

Lines changed: 3 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -8,32 +8,11 @@
88
* its entire purpose is to be used for performance-sensitive tasks.
99
*/
1010
export class MutationSensitiveArray<T> extends Array<T> {
11-
private readonly listeners: (() => void)[] = [];
12-
13-
once(listener: () => void): void {
14-
const wrapper = () => {
15-
listener();
16-
this.removeListener(wrapper);
17-
};
18-
this.addListener(wrapper);
19-
}
20-
21-
addListener(listener: () => void): void {
22-
if (!this.listeners.includes(listener)) {
23-
this.listeners.push(listener);
24-
}
25-
}
26-
27-
removeListener(listener: () => void): void {
28-
const index = this.listeners.indexOf(listener);
29-
if (index > -1) {
30-
this.listeners.splice(index, 1);
31-
}
32-
}
11+
onMutation: (() => void) | null = null;
3312

3413
private invalidate(): void {
35-
for (const listener of this.listeners) {
36-
listener();
14+
if (this.onMutation) {
15+
this.onMutation();
3716
}
3817
}
3918

0 commit comments

Comments
 (0)