The Organization of Event Handling in ThreeJs

I am facing the challenge of managing multiple instantiated objects, each requiring its own handling of a specific event.

Let's consider a class named "Foo":

export default class Foo() {
    constructor(eventManager) { //reference to an event manager class
       eventManager.eventPool.push(this.eventHandler);
       this.someProperty = 'hello world';
    }
    eventHandler(e) {
       // logic to handle passed-in event arguments
       console.log(this.someProperty); //any property I access is undefined, regardless of my efforts
    }
}

In addition, there is a static event handling class:

export default class EventManager() {
  constructor() {
     this.eventPool = [];
     window.addEventListener('mousemove', this.onMouseMove.bind(this), false);
  }
  onMouseMove(e) {
    if (this.eventPool.length > 0) {
      for (let i = 0; i < this.eventPool.length; ++i) {
        this.eventPool[i](e);
      }
    }
  }
}

Despite trying various approaches such as binding the eventHandler function to the class, when I attempt to call the eventHandler of a class and access its properties, they remain undefined. The dynamic nature of JavaScript, being untyped by default, adds complexity to the reference handling process.

This issue arises in the context of using Three.js to abstract event handling for user input on interactable items within a scene. While Three.js provides an EventDispatcher, it does not offer sufficient control over the event hierarchy. My goal is to construct intricate event chains that can be neatly managed within a class without requiring direct modifications to the source code.

How can I enable individual object instances to have their eventHandlers called from a central class managing all the references upon a specific event?

Answer №1

The main issue seems to be

for(let handler of this.eventPool)

this.eventPool is an array, and using for let eventHandler in will only iterate over the keys or indexes of the array, not the actual values. Consider using for let eventHandler of or accessing the value directly with

let eventHandlerValue = this.eventPool[eventHandler]
.

Answer №2

As I delved into three's source code, a revelation dawned upon me - a familiar pattern emerged...

The key to the solution lay not in binding the function beforehand, as I had attempted, but rather at the very moment of passing it into the array. In order for it to work effectively, it needed to be done WHEN YOU PASS IT INTO THE ARRAY, neither prior nor subsequent. To illustrate this concept, consider the following example....

export default class Foo(){
    constructor(eventManager){//reference to an event manager class
       eventManager.eventPool.push(this.eventHandler.bind(this))//bind the method while we pass it in
       this.someProperty = 'hello world'
    }
    eventHandler(e){ 
       console.log(this.someProperty) //now the function refrence will correctly access the instances properties
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can one determine the direction towards the camera from a vertex in a vertex shader using GLSL?

I'm working with the following code snippet: vec4 localPosition = vec4( position, 1.); vec4 worldPosition = modelMatrix * localPosition; vec3 look = normalize( vec3(cameraPosition) - vec3(worldPosition) ); vec3 transformed = vec3( position ) + look; ...

Tips for efficiently awaiting outcomes from numerous asynchronous procedures enclosed within a for loop?

I am currently working on a search algorithm that goes through 3 different databases and displays the results. The basic structure of the code is as follows: for(type in ["player", "team", "event"]){ this.searchService.getSearchResult(type).toPromise ...

Generating elements added at various depths within an HTML document with the help of JavaScript

create_new.append("div") .append("form").merge(update_5) .attr("action", d => d.market) .attr("target","_blank") .style("width","100%") .style("height","282") .append("input").merge(update_5) .attr("type","submit") ...

The API has been triggered twice

I am currently working on a React component where I have implemented an API call using the useEffect hook with an empty dependency array. However, I noticed that the API is being called twice and I can't seem to find the reason behind it. import { use ...

AngularJS - one-time execution of view generation from .NET controller

Currently, I have an MVC .NET application integrated with AngularJS. In my route provider configuration, I am utilizing the controllers of MVC to retrieve the views as shown below: .when('/Units', { templateUrl: 'Unit/Units' ...

Is there a workaround for unresolved symlink requirements when using npm link?

Creating an NPM package often involves using the following: npm link This allows for making modifications to a package called <myPackage> during development without constantly having to publish and unpublish! Developers can make changes locally and ...

The animation feature on the slideshow is dysfunctional

For this Vue component, I attempted to create a slideshow. The process is as follows: 1) Creating an array of all image sources to be included (array: pictures) 2) Initializing a variable(Count) to 0, starting from the beginning. 3) Adding v-bind:src=" ...

"Looking for a datetime picker plugin that works well with Bootstrap

Check out this efficient DateTimePicker example. <head> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script> <link rel="stylesh ...

What is the method to remove the overlay from view?

Can anyone help with a small issue I'm having? When I click on button one, a modal popup appears but the overlay doesn't disappear when unloading. I've tried the code below, but can someone suggest what might be causing the problem? var po ...

Assign a unique HTML attribute to a child element within a Material-UI component

Currently, I am trying to include the custom HTML5 attribute "data-metrics" in the span element within the ListItemText Material UI component. However, I am facing some difficulty achieving this as per the specifications outlined in the Component API Docum ...

An error popped up while using the fetch API due to an unexpected end of input

fetch('http://www.freegamesforyourwebsite.com/feeds/games/?tag=platform&limit=100&format=json', { method:'GET', mode:'no-cors', dataType: 'json', headers: { 'Accept': 'a ...

Validate if cookie has been established in Javascript

Hello everyone! I am trying to redirect a user to another page when a cookie is set by clicking a button. <a href="" onClick="SetCookie('pecCookie','this is a cookie','-1')"><button type="button" name="accept" clas ...

transforming basic pagination using javascript to jquery implementation

I have a straightforward pagination code written in raw JavaScript. function UpdatePage(e){ if(busy == 0) { switch(e) { case "Next": page = p+1; p++; break; ca ...

Utilize jQuery to target elements containing more than one class

Suppose an element has several classes as shown below: class="btn btn-primary add-movie-button is-on" Is it possible to select this element using only one class name with jQuery, for example: $(".add-movie-button") Can the method .hasClass("is-on") be ...

Leveraging jQuery to execute a post request and showcase the subsequent page seamlessly

I have set up a booking engine that utilizes a POST method. I incorporated the XDate library which is functioning perfectly. However, I am facing an issue where the booking engine is not displaying the new page from the booking engine website after executi ...

After completing the purchase, direct the user back to the HomePage

Currently, my development stack involves Reactjs for the UI and Java with Spring Boot for the backend. I have a specific question regarding user redirection after a purchase. For example, how can I direct the user back to the HomePage if they click the b ...

Eliminate element from collection utilizing singular term

Can you please advise on the best way to remove an element from an array without using the array index, such as array[0]? ...

javascript batch insert new key values

Is there a more elegant way to set multiple keys of an array in JavaScript? The current code may not be aesthetically pleasing, but it seems to be the only solution that works. var listData = []; listData['today'] = []; listData['data1&a ...

Create HTML div elements dynamically with JavaScript based on database information

Can javascript be used to create divs from database information? ...

"Exploring the process of making a REST call from an Angular TypeScript client to

I'm currently developing a Sessions Server for a project at work. My dilemma lies in the fact that I'm struggling to find resources on how to make JavaScript HTTP calls from a server running with http.createServer() and server.listen(8080, ...) ...