Using Threejs JSONLoader and OOP to easily add models to a scene post-loading

I am working on incorporating the THREE JSONLoader into a "Scenemanager" Object that manages the addition and removal of objects and models. My main goal is to deepen my understanding of OOP, JS, and Threejs.

Within App3D (which oversees the scene), I call the function to load the resource with the appropriate path and add it to both the scene and the objects array defined in the constructor. However, I keep encountering an 'undefined' error when using this.scene, leading me to believe that I may be overlooking a fundamental concept regarding how enclosures work in OOP/JS. Any assistance would be greatly appreciated.

app.js

window.onload = () => {

  let app = new App3D(); 
  app.loadModel('/assets/models/model.json');

}

In app3D, all the initializations for Threejs are carried out; scenes, lights, camera, renderer, and an array called actors are created to store all added objects.

app3D.js

class App3D{
  constructor() {
    this.loader = new THREE.JSONLoader();
    this.scene = new THREE.Scene();
    this.objects = [];

    this.createScene();
  }

  createScene(){
    // handles camera and renderer initialization, etc.
  }

  loadModel(model){
    this.loader.load(model, function(geometry, materials){
      let material = new THREE.MultiMaterial( materials );
      let mesh = new THREE.Mesh( geometry, material );
      this.scene.add(mesh);
      this.objects.push(mesh);
    });
  }

  render() {
   // includes request animation frame render logic, etc.
}

Answer №1

When using a combination of arrow functions () => { ... } and traditional functions function () { ... }, it's important to understand the differences between them, particularly with regards to the use of this. It would be beneficial to learn more about this topic by reading additional resources.

With an arrow function, the value of this is determined by where the function was defined:

class Foo {
  constructor (el) {
    var foo = this;
    el.addEventListener('click', () => {
      // foo === this
    });
  }
}

On the other hand, with a traditional function, the value of this is based on the calling object. Therefore, when using event listeners, it is usually necessary to bind the function or store the value of this in an external scope.

class Foo {
  constructor (el) {
    var foo = this;
    el.addEventListener('click', function () {
      // foo !== this
    });
  }
}

class Foo {
  constructor (el) {
    var foo = this;
    el.addEventListener('click', function () {
      // foo === this
    }.bind(this));
  }
}

In your loadModel function, make sure to properly handle the value of this by either storing it or binding it using one of the methods mentioned above.

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

Adding query parameters dynamically in Vue without refreshing the component

I'm attempting to update the Query Parameters in Vue without refreshing the component using Vue-Router. However, when I use the code below, it forces a component reload: this.$router.replace({query: this.filters}); Is there a way to prevent the comp ...

Renovating code structure in JavaScript

As I develop a small application that interacts with a database, I have opted to use Promises instead of the callback pattern for simplicity in my code. Through my coding experience, I've noticed a recurring pattern in my logic and I'm seeking ad ...

Determine if a key begins with a specific string within an object and retrieve the corresponding value

If I have an object like this: let fruitSong = {'apple song':12, 'banana song': 24} Object.keys(fruitSong).forEach(e=>{ if(e.startsWith('apple')){ console.log(fruitSong[e]) } }) Is there a different meth ...

Creating a hexagonal grid pattern with the use of texture

I have conducted several experiments in the past to determine the most effective way to create large-scale hexagon grids. I attempted drawing the hexagons using THREE.Line and THREE.LineSegments. While this method was successful for small grids, the perfo ...

In order to properly set up Require JS, you will need to configure the JS settings

Is there a way to specify the path from any property inside the require JS config section? We are trying to pass a property inside the config like so: The issue at hand: var SomePathFromPropertyFile = "CDN lib path"; require.config({ waitSeconds: 500 ...

Is it possible to include a value for the "src" attribute rather than the "class" attribute in the array of values in list.js?

Check out the HTML code I wrote: <html> <head> </head> <body> <input class="search" placeholder="Search" /> <div id="users"> <ul class="list"> ...

Updating information within AngularJS select boxes

On my page, I have 3 select boxes. When a user selects an option in the first select box, I want the options in the second select box to update based on the value selected in the first one. Similarly, I want the options in the third select box to change w ...

What is the best way to find the average time in Typescript?

I am dealing with an object that contains the following properties: numberOfReturns: number = 0; returns_explanations: string [] = []; departure_time: string = ''; arrival_time: string = ''; The departure_time property hold ...

Could not locate the express.js file

Currently in the process of learning express/node.js, but struggling to locate the page at localhost:3000/info You can view screenshots of my code below ...

Error: JSON array contains unterminated string literal

Hey there, var favorites = 'Array ( [0] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "] [1] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "] [2] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "] ) '; I've been encountering a syntax error - an untermi ...

Having difficulty executing the command 'npm install -g expo-cli'

When attempting to execute npm install - g expo-cli on a Windows 10 machine, I am encountering issues. An error message keeps popping up and preventing me from proceeding. I'm in desperate need of assistance! npm WARN deprecated <a href="/cdn-cgi/ ...

Node.js: Obtain the type of file

Hey everyone, I am currently working on a project in Node.js where I need to extract the file type. This is necessary as I have to rename the file before uploading it for version control and then perform some processing tasks on it. Although I know that c ...

Show the "Splash" picture, then switch to a newly uploaded image and show it for a set amount of time

I am in the process of developing an HTML/JavaScript page that will showcase a splash image (splash.jpg) until it gets replaced by another image file called latest.jpg. Once this latest.jpg is displayed, I want it to remain on the screen for 90 seconds bef ...

Angular 5 is throwing an error that says: "There is a TypeError and it cannot read the property 'nativeElement' because it

Being aware that I may not be the first to inquire about this issue, I find myself working on an Angular 5 application where I need to programmatically open an accordion. Everything seems to function as expected in stackblitz, but unfortunately, I am enco ...

Utilizing a function that changes a UNIX timestamp to a month/day/year layout

I have been working with ExpressJS and am facing a challenge in converting the UNIX format date to mm/dd/yyyy format when retrieving the date value. I attempted to create a function for this conversion, but encountered an issue where my methods cannot be c ...

Transforming a menu tab into an active anchor when navigating to a particular section

Hello, I have successfully created a JavaScript code that can dynamically add menu tabs into the menu list window.addEventListener("load", () => { const navList = document.getElementById("nav_list") const fragment ...

What could be causing the npm install command to not save packages in the /node_modules directory?

After running npm install to add a package, npm indicates that the installation was successful. However, upon checking the node_modules folder, I'm unable to locate the installed package. In order to access the package, I have resorted to using npm in ...

Is it possible to convert a string of elements in JavaScript into JSON format?

Within my JavaScript code, a variable holds the following information: url=http://localhost quality=100 tag="4.4, 5.5" I am interested in converting this data to JSON format using JavaScript, like this: "result": { "url": "http://localhost", "qu ...

Implementing an Onclick function in HTML

I have an HTML code and I am looking to add an onclick event for a button named GET DATA. When the button is clicked, I want to send data for userId and categoryId to a PHP file. Can someone help me implement this functionality in my existing code? Here ...

Importing JavaScript files to work with Vue-Router: A Step-by-Step Guide

Seeking guidance on importing JavaScript files correctly throughout my Vue project, including within the components used to implement changes with Vue-Router. Currently, encountering an issue where I must reload the component in order for the JavaScript to ...