Utilizing JavaScript function parameters with the power of Three.js

My question involves an Object with 2 parameters - Obj3D and Name, and I am trying to load the object by its name:

function load3DObjectByName(obj, loader)
{
    loader.load(
        "resources/3D/meshes.dae",
        function(collada) {
            obj.Obj = collada.scene.getChildByName(obj.Name, true);
            window.alert(obj.Obj["name"]); // obj.Obj is not undefined
    }
    );
     window.alert(obj.Obj["name"]); // obj.Obj is undefined
}

Unfortunately, even after loading, obj.Obj remains undefined... where the loader used is ColladaLoader.

Answer №1

When the function loader.load is asynchronous, it means that the object will not be immediately populated after the function call. To put it simply:

load3DObjectByName(obj, loader);
//obj might still be initializing.

To handle this situation, you can either use a promise or continue using CPS.

function load3DObjectByName(obj, loader)
{
    return new Promise(function(resolve) {
        loader.load(
            "resources/3D/meshes.dae",
            function(collada) {
                obj.Obj = collada.scene.getChildByName(obj.Name, true);
                resolve(obj);
            }
        );
    });
}

var prom = load3DObjectByName(obj, loader);
prom.then(function(obj){
    //Now you can use the fully populated obj here.
});

Answer №2

In accordance with MinusFour's observation, it is crucial to note that loader.load operates asynchronously. Essentially, this implies that the code executes in the following sequence:

loader.load(..., youranonymousfunctionReference)
window.alert(...
// subsequently in event loop
youranonymousfunctionReference.

Consequently, when window.alert is triggered, the anonymous function has yet to be executed, resulting in an undefined value for Obj.

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

Loop through an array in JavaScript to create properties for an object

When working with Vue, I encountered a prop that is actually an array containing multiple types of items. For each item in this array, I want to create a property in a specific object. For example, if the array includes methods and count, I aim to construc ...

Over-extended Affix in Bootstrap 3.1.0

I'm currently using Bootstrap 3.1.0. The issue I've encountered is that when the "affix" becomes too long for the viewport, it ends up getting cut off and doesn't display the bottom items. Is there a way to make Bootstrap's affix featu ...

Creating a function to update data in a Node.js/MongoDB environment

Hey there! I'm new to working with nodejs and mongodb, and I'm trying to create a function that updates the win, lose, and draw record in my UserSchema. Here's my Schema: UserSchema = new mongoose.Schema({ username:'string', ...

TypeError thrown by Basic TypeScript Class

I'm encountering an issue where TypeScript is throwing a TypeError when trying to use the class Literal from file Classes.tsx in file App.tsx, even though they are in the same file. Strangely, everything works fine on typescriptlang.org/play. // Class ...

What could be causing a parse error and missing authorization token in an AJAX request?

I recently wrote some code to connect a chat bot to Viber using the REST API. The main part of the code looks like this -: $.ajax({ url : url , dataType : "jsonp", type : 'POST', jsonpCallback: 'fn', headers: { 'X-Viber-Auth- ...

Choose the specific selector following the current selector

Consider this example of code: <script> $(document).ready(function () { $('span').each(function () { $(this).html('<div></div>') ; if ( $(this).attr('id') == 'W0' ...

How to hide the header on a specific page using Angular

Currently, I am working on an Angular project and my requirement is to hide the header block specifically on the login page. Despite attempting to hide the header on the login page, it seems that my efforts have been unsuccessful so far. Is there anyone wh ...

How can a function work with an array of subarrays of objects without altering the original array?

Within a small coding project I recently completed, I handled an array consisting of 3 subarrays, with each subarray containing 4 objects. I passed this array through a function that gradually removes values from each subarray until only 1 object remains i ...

Using Vuetify Select with Vuex getters

I am having an issue with my Vuex implementation. I have a getter that retrieves an array which I use in a Vuetify drop down select component. My goal is to insert an additional property at the beginning of the array, but when I try to do so, only a number ...

Learn how to dynamically assign a new ID and name to a cloned div element using jQuery based on the original element's ID

Within a DIV, there are two Input Textboxes present. I am attempting to duplicate the above div, meaning I want two additional textboxes cloned from the original ones. However, I am encountering challenges when it comes to assigning new IDs and Names to ...

Steps for displaying a JSX component for every element in an array

I have a requirement to display a unique jsx component for each element in an array. import { ListView } from './components'; // Custom component const array = ["item1","item2","item3"]; export default function App ...

Utilizing jQuery datepicker to extract data from a database and trigger an Alert: A tutorial

I want to create an alert that pops up when someone chooses a specific date on a calendar. The information displayed in the alert needs to be retrieved from a database, not just showing the selected date. I have been able to display a basic alert, but I ...

Corrupted file download after exporting Web API data to Excel

I utilized OfficeOpenXml ExcelPackage to create an excel file from a list of Objects. The download is successful, but upon opening the file, Excel issues a warning that it is corrupted and not saved in the proper file format. I also attempted using FileSav ...

Updating the background image with Jquery is resulting in a distracting flicker effect

Here is a snippet of the script I'm using to create a slider that changes the background image for each image object in a specified time cycle. #Sliderimg - height set to 500px, $("#Sliderimg").css({ "background-image": "url(../Images/" + SliderIma ...

Steps for referencing a custom JavaScript file instead of the default one:

Currently, I am utilizing webpack and typescript in my single page application in combination with the oidc-client npm package. The structure of the oidc-client package that I am working with is as follows: oidc-client.d.ts oidc-client.js oidc-client.rs ...

Updating the price in real-time using JavaScript or jQuery based on the selected option

I am seeking a way to dynamically update the content of a span that is meant to show the price of the selected option. Just a note, I am utilizing Django + Python for generating the options. Below is my code snippet : <select class="form-control" id=" ...

What is preventing me from generating Face3 in my ThreeJS Typescript project

Currently, I'm in the process of generating a Mesh using Face3 within a TypeScript project that utilizes Three.js. However, I've encountered a few issues along the way. const points = [ new Face3(-1, 1, -1),//c new Face3(-1, -1, 1),//b ...

Converting an Array with Key-Value pairs to a JSON object using JavaScript

After using JSON.stringify() on an array in JavaScript, the resulting data appears as follows: [ { "typeOfLoan":"Home" }, { "typeOfResidency":"Primary" }, { "downPayment":"5%" }, { "stage":"Just Looki ...

Error: Attempting to access property 'navigate' of an undefined variable is not allowed

Hey there, evening everyone! I'm facing a bit of an issue when trying to click on the "login or register button" as I'm getting this error message: "TypeError: Cannot read property 'navigate' of undefined" I've made some small ad ...

The process of triggering an action after three mouse clicks

I'm fairly new to coding and I'm currently trying to solve a problem where a div should disappear after being clicked three times. I've managed to achieve this for one or two clicks, but getting it to work for three clicks is proving to be a ...