Main query
I've encountered an issue where an event emitted on one class supporting EventDispatcher is not detected by another class also supporting EventDispatcher. How can I establish app-wide communication to efficiently pass messages between different classes?
Currently, it seems that message passing is limited to within the same class only.
Context
The framework I'm working with provides three.js and ES6 through this boilerplate:
https://github.com/paulmg/ThreeJS-Webpack-ES6-Boilerplate
I have manually updated the packages to incorporate version r97 of three.js.
I am exploring the EventDispatcher class as a means to facilitate messaging across the system while maintaining loose coupling. For instance, I have UI elements monitoring user interactions like checkboxes.
Simplifying it to its essence, I have interaction.js:
import {EventDispatcher} from 'three';
// Handles all interactive inputs
export default class Interaction {
constructor() {
// Enabling event dispatcher support
Object.assign( this, EventDispatcher.prototype );
// Defining the event trigger
let outer = this;
$("#" + Config.uiElements.boxOpenStateId).change(function() {
console.log("event emitting");
outer.dispatchEvent( { type: 'boxOpenStateToggled', message: { isChecked: "example" } } );
console.log("event emitted");
});
// Setting up an event listener
this.addEventListener( 'boxOpenStateToggled', function ( event ) {
console.log("event caught in Interaction.js", event);
});
}
}
And similarly, boxmanager.js (streamlined):
import {EventDispatcher} from 'three';
export default class BoxManager {
constructor() {
// Enabling event dispatcher support
Object.assign( this, EventDispatcher.prototype );
}
setupBoxes(manager) {
console.log("adding event listener on BoxManager.js");
this.addEventListener( 'boxOpenStateToggled', function ( event ) {
console.log("event caught by BoxManager.js", event);
} );
}
}
Upon triggering the boxOpenStateToggled
event in Interaction
, the BoxManager
fails to capture the event.
In the console, the log shows:
adding event listener on BoxManager.js
adding event listener on Interaction.js
(Event is triggered)
event emitting
event caught in Interaction.js {type: "boxOpenStateToggled", message: {…}, target: Interaction}
event emitted
I anticipated seeing "event caught in BoxManager" as well - should the event dispatcher work globally or does it operate within individual classes?
Tests & Analysis
To rule out any potential misuse, I experimented with:
employing the
extends
keyword for granting theEventDispatcher
functionality, which functions but confines to the class boundaries.initially utilizing the
.call
variant present in an earlier three.js release.
I couldn't find substantial discussions or instances of using EventDispatcher within the library. Am I misinterpreting its intended use? Is my implementation incorrect?