The ThreeJS model loader encountered an error while attempting to load within a class method

Currently, I am in the process of constructing a ThreeJS scene and coding it as a class:

export class RenderCanvas {

    #scene; // THREE.Scene()

    // Other properties and methods

    loadGeometries() {
        /* #scene is initialized before loadGeometries is called */ 

        var modelLoader = new FBXLoader();
        for (let path of listOfObjects) {
            modelLoader.load(path,
                function (obj) {
                    obj.traverse(function (child) { /* did nothing */ });
                    this.#scene.add(obj); 
                },
                function (xhr) {
                    console.log((xhr.loaded / xhr.total * 100) + "% loaded")
                },
                function (err) {
                    console.error("Error loading the object")
                }
            )
        }
    }

In a separate JS file, an instance of the RenderCanvas class is created and the loadGeometries() method is invoked.

The issue arises when the console shows that the model has been loaded to 100%, yet the Error loading the object message is displayed.

Upon further investigation, I observed that if I utilize the procedural approach instead of Object-Oriented Programming (OOP) and declare scene as a global variable, then the model loader functions correctly. This leads me to believe that there might be an issue with this.#scene.add(obj); not having the proper context, though I am uncertain if this hypothesis is accurate or how to resolve it.

Can you pinpoint what caused this problem and provide guidance on how to rectify it?

Answer №1

It appears that the reference for this is incorrect within the onLoad() callback function. To resolve this issue, consider storing the this reference in a variable called scope. Here's an example:

loadGeometries() {
    /* #scene is initialized before loadGeometries is invoked */ 

    var modelLoader = new FBXLoader();
    var scope = this;
    for (let path of listOfObjects) {
        modelLoader.load(path,
            function (obj) {
                obj.traverse(function (child) { /* No actions performed */ });
                scope.#scene.add(obj); 
            },
            function (xhr) {
                console.log((xhr.loaded / xhr.total * 100) + "% loaded")
            },
            function (err) {
                console.error("Error loading the object")
            }
        )
    }
}

Another option is to use an arrow function instead of a regular function as it preserves the correct this context.

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

Exclude certain APIs from utilizing basic authentication in Fastify

I currently have two APIs set up: /auth and /no-auth. My goal is to only use basic authentication for one of them. To implement this, I am using the fastify-basic-auth plugin with fastify in a node environment. The /auth route should require authenticat ...

initially chosen from a concealed drop-down menu

I need to set a default value for a dropdown select. For example, the krik value is ('pt123', 'washington', 'rob case', 'rob', 'rob'). I want the selection to be based on val4, which is the call card id. ...

Creating two separate divs that can scroll independently while also limiting each other's scroll depth can be achieved by utilizing

I am attempting to replicate the unique scrolling feature seen on this particular page. Essentially, there are two columns above the fold that can be scrolled independently, but I want their scroll depths to be linked. When a certain depth is reached whil ...

What is the method for viewing the available choices in a select2 instance?

I am trying to retrieve the options configured in a select2 instance, specifically the value of the allowClear option whether it is true or false. Upon exploring the object, I located the allowClear option in jQuery... -> select2 -> options -&g ...

Trying to find a more efficient method to export multiple classes as an array in typescript

I've organized my files like this: index.ts folder/ a.ts b.ts subfolder/ c.ts d.ts e.ts ... In each file, there is one default exported class and I want index.ts to export all these classes as an array. Currently, I achieve thi ...

What is the best way to create dynamic transparency based on cursor position?

Is there a way to create an animation like the one on https://meetwalter.com, where the transparency changes with the cursor's position? I previously attempted a similar implementation using CSS, but it seems that the website accomplishes this effect ...

Issue with determining the time complexity of the provided code

Can you determine the time complexity of this code snippet? response: O(log2n) explanation: By looping with i=0; while i is less than n; incrementing i*2, the loop continues indefinitely until the condition becomes false see image here ...

Is it possible to access global variables within a composable function?

I am currently in the process of transitioning a project from Vue 2 options API to Vue 3 composition API. Within an options API component, there is a variable named componentData. I am calling a mixin from this component, which allows me to access all the ...

"Step-by-step guide to layering an HTML element on top of another with CSS

I am facing an issue with positioning a small icon over a slider using HTML and CSS. The problem arises because both the slider and the icon have a position absolute, causing the slider to hide the icon. Here is the CSS code for the icon: #nav { po ...

How can I create a real-time page update using node.js?

I am completely new to node.js, but my main goal in learning this language is to achieve a specific task. I want to create a webpage where the content within a designated "div" can be swapped dynamically for users currently viewing the page. For example, ...

Chrome experiencing stuttering issue with jQuery's .slideUp() function

When I click a button, I want to hide certain elements in my HTML document. $(document).on('mouseup','#button',function() { setTimeout(setupBox1,100); setTimeout(setupBox2,Math.floor((Math.random() * 3000) + 800)); setTimeo ...

Is it possible for CSS to incorporate <META> tags?

When added through the use of <link>, CSS files are typically placed within the <head> section of an HTML document without the need for <style> tags. At present, I have both the <script> and <meta name=viewport> elements posit ...

Implementing a Standardized Template for Consistent Design and styling Throughout Website

As I work on building my website, I find myself struggling with some of the intricacies. The homepage is set up with a navbar and header, along with several pages that can be easily navigated to. While everything seems to be functioning properly, upon ins ...

The response from Axios in NodeJs is displaying incorrect encoding

Having some trouble executing a REST call using Axios and receiving an unexpected response. try { const response = await axios.get("https://api.predic8.de/shop/products/"); console.log(response.data); } catch (error) { console.log(`[Error] -> ...

Using Tesseract.js to process local files is not supported

When utilizing tesseract.js on a URL, it functions correctly. However, when attempting to run it on a local file, I encounter errors. How can I troubleshoot this issue? I am currently using tesseract.js v2.1.0 and below is the code snippet: const { create ...

Accessing elements of both arrays and objects can be done by iterating through them using one code

Suppose I have a function that receives either an object or an array. The goal is to iterate through each element and perform some action on each element along the way. While looping through an array can be achieved using forEach() or a regular for loop, h ...

The Ajax data was not displayed in the console log, instead an error message was returned stating "http://localhost/IFICSV3/public/sla/sla/getbranch/180 not found"

I am attempting to make a dropdown option dependent on another using ajax. I want to view the data in the console to see if it is successful or not. I expect the data to be displayed in the console log, but instead, an error is being given. http://local ...

How can I invoke a custom function asynchronously with JavaScript?

Incorporating a specific angular third party module into my application has posed some challenges. This module offers various call-back methods such as login success and failure, where I have embedded my custom scripts for execution. However, the current ...

Transmitting unique characters, such as a caron symbol, via xmlhttp.responseText and encoding them with json_encode

I am struggling to retrieve data from a database that contains a special character (caron) and then pass it through xmlhttp.responseText using json_encode to fill textboxes. However, the textbox linked to the data with the special character (caron) is not ...

What is the best way to implement a bootstrap progress bar without using any JavaScript libraries, or if necessary, using a

Can we simplify the creation of a progress bar using JavaScript only? progressBarElem = document.createElement("div"); progressBarElem.className = "progress-bar" progressBarElem.setAttribute("role","progressbar") progressBarElem.setAttribute("aria-valueno ...