Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

Scene: Object3D.dispatchEvent clears event.target after the listeners run, as three.js does (#115)

Kevin Rajane00b06f32de6
diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.ts
index afbefdb..83f8695 100644
--- a/packages/scene/src/core.ts
+++ b/packages/scene/src/core.ts
@@ -114,7 +114,7 @@ export interface PhysicsDesc {
/** An event of an object (`addEventListener`). */
export interface ObjectEvent {
type: string;
- target?: Object3D;
+ target?: Object3D | null;
[key: string]: unknown;
}
@@ -512,6 +512,7 @@ export class Object3D {
if (!l?.length) return;
event.target = this;
for (const f of [...l]) f(event);
+ event.target = null;
}
set id(v: string | number | undefined) {
this._id = v === undefined ? undefined : String(v);
diff --git a/packages/scene/test/three-compat-events.test.ts b/packages/scene/test/three-compat-events.test.ts
new file mode 100644
index 0000000..d5bb61b
--- /dev/null
+++ b/packages/scene/test/three-compat-events.test.ts
@@ -0,0 +1,27 @@
+// three.js compatibility: Object3D.dispatchEvent clears the event target, as three.js r187 has it (the snippet-level suite is three-compat.test.ts).
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "../src/index.ts";
+
+test("Object3D.dispatchEvent: target is cleared after listeners run, as three.js does", () => {
+ const first = new THREE.Object3D();
+ const second = new THREE.Object3D();
+ const event: { type: string; target?: THREE.Object3D } = { type: "ping" };
+ const called: string[] = [];
+ first.addEventListener("ping", (e) => {
+ assert.equal(e.target, first, "listener sees the dispatcher as its target");
+ assert.equal(e, event, "the original event object is passed through");
+ called.push("first");
+ });
+ second.addEventListener("ping", (e) => {
+ assert.equal(e.target, second, "a reused event targets its current dispatcher");
+ assert.equal(e, event);
+ called.push("second");
+ });
+
+ first.dispatchEvent(event);
+ assert.equal(event.target, null, "target is null after the first dispatch");
+ second.dispatchEvent(event);
+ assert.equal(event.target, null, "target is null after the second dispatch");
+ assert.deepEqual(called, ["first", "second"]);
+});