The property of the object array type is not defined in another document

Currently, I am in the process of restructuring a JavaScript file that utilizes the THREE.js library to create a truck visualization based on input parameters from a form. Although the code was functioning properly, I aim to enhance it with additional visualizations, hence my decision to clean it up beforehand. To accomplish this, I constructed an object within the scene.js file as shown below:

import * as THREE from "three";
import jQuery from 'jquery';

window.$ = jQuery;

const sceneObject = {
    renderer: new THREE.WebGLRenderer(),
    backgroundColor: new THREE.Color(255, 255, 255),
    scene: {},
    camera: {},
    center: {
        x: 100,
        y: -200,
        z: -500
    },
    cameraRadius: 770,
    angle1: 3*Math.PI/4,
    angle2: 0,

    prepare:  function(width, height,divId = 'placeForRenderer'){
        this.prepareScene();
        this.prepareCamera();
    },

    prepareScene: function(width, height, divId){
        this.scene = new THREE.Scene();
        this.scene.background = this.backgroundColor;
        this.renderer.setSize(width, height);
        $('#'+divId).append(this.renderer.domElement);
    },

    prepareCamera: function(){
        this.camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 2000);
        this.camera.position.set(this.center.x + this.cameraRadius * Math.cos(this.angle1), this.center.y + this.cameraRadius * Math.sin(this.angle2), this.center.z + this.cameraRadius * Math.sin(this.angle1));
        this.camera.lookAt(this.center.x, this.center.y, this.center.z);
    },

    addObject: function(object){
        if(typeof(this.objectsArray) == 'undefined') {
            this.objectsArray = [];
        }
        this.objectsArray.push(object);

        console.log(this.objectsArray);
    },

    show: function(){
        console.log(this.objectsArray);
        this.objectsArray.forEach((object) => {
           object.addToScene(this.scene);
        });
        this.renderer.render(this.scene, this.camera);
    }
};

export default sceneObject;

In another file named all.js, I invoke the function that readies the scene, add an object (which will eventually be kept in separate files — currently only one is added for testing purposes), and finally call the rendering function. This calling sequence serves primarily for testing purposes but also aligns with regular practice when modifying drawing parameters:

import sceneObject from './scene'
import * as THREE from "three";

sceneObject.prepare(500, 300);
sceneObject.addObject({
    addToScene: function(scene){
        const geometry = new THREE.BoxGeometry(200, 200, 200);
        const mesh = new THREE.Mesh(
            geometry,
            new THREE.MeshBasicMaterial({transparent: true, opacity: 0.0})
        );

        const borders_geo = new THREE.EdgesGeometry(geometry);
        const color = new THREE.Color(0xEB7F46);
        const mat = new THREE.LineBasicMaterial({color: color});
        let borders = new THREE.LineSegments(borders_geo, mat);
        borders.renderOrder = 1;
        mesh.add(borders)
        scene.add(mesh);
        mesh.position.set(100, -200, -500);
    }
});

sceneObject.show();

export default sceneObject;

Lastly, there is the admin.js file which is included in the appropriate HTML document. Here are the lines of code found in it:

import jQuery from 'jquery';
import scene from './functions/common/all.js';

window.$ = jQuery;

$(document).ready(()=>{
    $("#car-length-input").on('change', scene.show);
    $("#car-width-input").on('change', scene.show);
    $("#car-height-input").on('change', scene.show);
    $("#car-dmc-input").on('change', scene.show);
})

The issue I encountered involves calling the show function in admin.js, resulting in the objects array within the scene becoming undefined: https://i.sstatic.net/XImHJG9c.png I have combed through various resources online in search of a solution, however, so far, none have proven fruitful.

I attempted placing objectsArray both inside the function (as currently done) and at the top of the object as a parameter. I also inserted console.log statements at different points in the code to monitor varying values in distinct files. Ultimately, my objective is to utilize the addObject function to include specific objects in the scene and present them using the show function across different files.

Answer №1

Through thorough investigation and the strategic placement of console.log statements, I was able to identify and resolve the issue at hand. It became clear that the parameter was not being lost during file transitions, but rather when the show function was called as an event listener. This realization pointed towards the incorrect usage of the show function in this context. By replacing

$("#car-length-input").on('change', scene.show);
$("#car-width-input").on('change', scene.show);
$("#car-height-input").on('change', scene.show);
$("#car-dmc-input").on('change', scene.show);

with

$("#car-length-input").on('change', ()=> { scene.show() });
$("#car-width-input").on('change', ()=> { scene.show() });
$("#car-height-input").on('change', ()=> { scene.show() });
$("#car-dmc-input").on('change', ()=> { scene.show() });

the function executed correctly and yielded an array of objects.

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

Running the command "npm install [package]" does not automatically update the package.json file

I'm currently utilizing Laravel and experimenting with angular-ui-sortable and angular-utils-pagination. I have successfully installed them using npm, however, I am facing difficulties in updating the package.json file for angular-utils-pagination. ...

Learning to retrieve JSON data from an API using JavaScript

https://i.sstatic.net/OQZvD.pngGreetings! I am currently facing an issue while trying to retrieve JSON data from an API. Whenever I attempt to extract data from the API, everything works smoothly except for when I try to access the distance value, which re ...

Showing text instantly upon clicking a radio button, in real-time

I'm working with a set of radio buttons that are linked to numbers ranging from 1 to 24. I need to show the selected number in another part of the page when a radio button is clicked. What would be the best way to achieve this? ...

The 'void' data type must be equipped with a '[Symbol.iterator]()' function that produces an iterator

Whenever I execute the post() function below, it triggers an error message stating: Type 'void' must have a '[Symbol.iterator]()' method that returns an iterator. This is the code snippet causing the issue: static async post(options: ...

Update the directory path for Angular ui-bootstrap templates

Currently, I am attempting to utilize ui-bootstrap.min.js in conjunction with external templates. An issue has arisen where the error message reads as follows: http://localhost:13132/Place/template/timepicker/timepicker.html 404 (Not Found) I desire fo ...

What is the process for rotating a vector around a random axis?

Imagine I have an imaginary axis created by two vectors. For instance, one vector points upwards at x = 10: const startingPosition = new Vector3(10, 0, 0) const endPosition = new Vector3(10, 0, 1) To find the direction of this axis, you can do the followi ...

Code in jQuery or JavaScript to retrieve precise node information for the currently selected form field, text, or image on a webpage

Looking to retrieve specific information about the item that has been clicked on a web page using jquery. The clickable item could be a form element (like a checkbox, text box, or text area) or a section of text within a paragraph, div, list, or image... ...

Use JavaScript's Array.filter method to efficiently filter out duplicates without causing any UI slowdown

In a unique case I'm dealing with, certain validation logic needs to occur in the UI for specific business reasons[...]. The array could potentially contain anywhere from several tens to hundreds of thousands of items (1-400K). This frontend operation ...

Challenges encountered when bringing in modules from THREE.js

Is there a way for me to import the custom geometry file called "OutlinesGeometry.js" from this link? I've attempted to import it like this: <script type="module" src="./three/build/three.module.js"></script> <scrip ...

What is the recommended element for managing data in React?

Let's consider a scenario where we have 2 main components: class App extends React.Component { state = { comments: [1, 2, 3, 4] } render() { return ( <Comments /> ) } } class Comments extends React.Component { rende ...

What steps should I follow to ensure that the processData function waits for the data returned by the getData function in Angular?

After calling the getData function, each object is stored in an array and returned. Now I need the processData function to await these results from getData and then further process them. However, when I try to console.log(cleaningData), I don't see an ...

AngularJS Datepicker with parentheses in the Controller.js

I recently started working with angularJS in Brackets and I am attempting to implement a datepicker from https://codepen.io/anon/pen/ZvVxqg However, when I paste the JS file into my controller.js in Brackets, an error occurs. Below are the code snippets ...

Utilizing React to bind "this" to a method within a class

Currently, I am immersed in a React book that suggests binding methods like this: this.onClickMe = this.onClickMe.bind(this); However, the functionality seems to work perfectly fine without including the above code snippet. class ExplainBindingsComponen ...

inability to conceal a two-dimensional marker array within Google Maps API v3

I need some help with my marker that refuses to hide Even after using setMap, my marker is still visible on the map Here is the error message from the console Please assist! Thank you in advance markers[i][j].setMap(null); markers.setMap(null); va ...

Deciphering C character array sent via a web server to extract (JSON or JavaScript) data fields

Objective: I want to transfer a struct of GPS data from C via a web server and have it displayed on a web page with details like latitude, longitude, etc. Tools Used: Linux operating system, libwebsockets (LWS) library for the web server. The C code is in ...

Error: The array geocode-api encountered an IndexOutOfRangeException, indicating that the specified index was beyond the allowable bounds

I encountered an "index was outside the bounds of the array" exception while trying to retrieve the latitude value from a geocode request on this line of code: string strLat = myCoordenates.Results[0].Geometry.Location.Lat.ToString(); The purpose of this ...

Retrieve the most recent score of authorized players using the Google Game API and Node.js

How can I display the last score of a specific game using the Google Play Game API? For example, I am looking to retrieve the latest scores of authenticated users playing "Rush Fight" with NodeJS. Any suggestions on how to achieve this? ...

What techniques can be used to avoid the MUI `DataGrid` from constantly re-rendering when a row is committed?

Check it out here to see how the MUI documentation implemented it: <b>const</b> rows = [/* Row Data */] <DataGrid rows={rows} {/* Other Props */} /> <sup>/*[1]*/</sup> The approach taken by MUI is quite impressive. It streaml ...

The specified type '{}' cannot be assigned to type 'ReactNode'

Can someone help me figure out why I am getting this error in Vercel but not locally? Error: 'FontAwesomeIcon' cannot be used as a JSX component. ./components/Services/ServiceContainer.tsx:25:6 12:01:54.967 Type error: 'FontAwesomeIcon&a ...

Verification of email address is required, emails must be unique and not duplicated

I am working on validating email addresses to ensure they are not repeated. So far, I have successfully pushed them from the server into an array using regex for validation. What steps should I take next to compare and further validate these emails? ...