Crafting dynamic objects with THREE.JS

I am working with a JSON configuration that looks like this:

{ shape:[ 'SphereGeometry', [7, 16, 16] ] }

My goal is to load a model using the following code:

new THREE[shape[0]].apply( this, shape[1] )

However, it seems that using "new" and "apply" is not an option in this scenario. I am wondering if anyone has any suggestions or tips on how I can work around this issue?

Thank you in advance.

Answer №1

The solution relies on a discussion about using the .apply() method with the 'new' operator, as highlighted in this Stack Overflow post.

Here is the JSON configuration:

{ shape: 'SphereGeometry', properties: [ null, 7, 16, 16 ] }

This involves creating a new object like so:

new (Function.prototype.bind.apply( THREE[object.shape], object.properties ))

Answer №2

Utilizing .apply() along with new simultaneously may not be the most elegant process, but here is an example of how it can be done:

function createDynamicShape() {
    return THREE[shape[0]].apply(this, shape[1]);
}
createDynamicShape.prototype = THREE[shape[0]].prototype;

var customShape = new createDynamicShape();

This implementation should function correctly. To see a working example, check out this fiddle with some sample code: http://jsfiddle.net/jcc6zbtn/

Answer №3

Check out this alternative method using a reviver function. The great thing about this approach is that the parsing process handles object instantiation directly, eliminating the need for multiple steps.

let shapeTypes = { 'Rectangle': Rectangle }, //similar to THREE in your original code
    jsonShape = '{ "shape": ["Rectangle", [2, 4]] }',
    createdShape = createShapeFromJson(jsonShape);

console.log(createdShape);

function instantiateObject(constructor, arguments) {
    let instance = Object.create(constructor.prototype);
    constructor.apply(instance, arguments);
    return instance;
}

function createShape(type, parameters) {
    return instantiateObject(shapeTypes[type], parameters);
}

function createShapeFromJson(jsonString) {
    return JSON.parse(jsonString, function (key, value) {
        return key ? value : createShape(value.shape[0], value.shape[1]);
    });
}

function Rectangle(height, width) {
    this.height = height;
    this.width = width;
}

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

Identifying a failed Ajax Request in JavaScript

How can I check if an Ajax request failed to load a file? Here is the code I'm currently using: var pro = undefined; var xmlhttp; if (window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); } else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTT ...

Despite the presence of data within the array, the React array returns empty when examined using the inspect element tool

Currently, I'm working on creating an array of objects in React. These objects consist of a name and a corresponding color, which is used to represent the pointer on Google Maps. For instance, one object would look like this: {name: "Ben", colour: "gr ...

An unforeseen issue occurred while trying to access an indexed element ID

I've recently started learning javascript and jquery, and encountered a problem while working on a script. The script is created by php code that reads lines from a file, processes them, and displays them using arrays. In addition, javascript validat ...

Ways to retrieve my PHP output and display it on a page using Ajax

I'm struggling to combine the functionalities of a PHP script and Ajax on my website. I want to update content without reloading the page but facing issues. Although I can send input data through Ajax, I'm unable to retrieve the results effectiv ...

Using AngularJS to send a post request with cherrypy

I am facing an issue with posting events into a CherryPy small application that responds to GET/POST requests. When attempting to do so using AngularJS, nothing gets posted. I'm unsure if the problem lies with AngularJS or CherryPy (CP). Cross-domain ...

elevate the div with a floating effect

My goal is to create a chat feature for users that will only be visible for a limited time period. I was thinking of using PHP and timestamp to achieve this functionality, but I also want to make the chat visually disappear by having the message div float ...

Removing buttons from a table row dynamically

Below is how I am adding the Button to Element: (this.sample as any).element.addEventListener("mouseover", function (e) { if ((e.target as HTMLElement).classList.contains("e-rowcell")) { let ele: Element = e.target as Element; let ro ...

What is the best way to access the camera of a mobile phone through a web application?

Whenever I try to access the camera on my mobile device through a web app, I encounter an issue. While the camera works perfectly fine on the web version, it fails to show up on my mobile device unless I add https:// in the URL. How can I resolve this prob ...

Guide to excluding all subdependencies using webpack-node-externals

My current setup involves using webpack to bundle both server assets and client code by specifying the target property. While this configuration has been working well, I encountered an issue where webpack includes all modules from node_modules even for ser ...

Tips for implementing pagination in a search result by adjusting the skip and limit values within the same query

While some may argue that this question belongs on programmers.stackexchange.com, after reviewing the Help Center of Stack Overflow, I believe it is a specific programming issue and will likely receive a better response here. I have developed a webapp usi ...

What is the best way to download the entire page source, rather than just a portion of it

I am currently facing an issue while scraping dynamic data from a website. The PageSource I obtain using the get() method seems to be incomplete, unlike when viewing directly from Chrome or Firefox browsers. I am seeking a solution that will allow me to fu ...

Issue locating the bottom of the scroll bar

My attempt to detect when the scroll reaches the bottom of a div involves using this code: $('.scrollpane').scroll(function(){ if ($(this).scrollTop() + $(this).height() === $("#results").height()) { alert('scroll at bottom&a ...

The issue of `for` loop and `forEach` loop not functioning in EJS

I'm currently developing a To-Do App and facing difficulty with the POST request functionality. I've attempted using both a for loop and a forEach loop but none seem to be working. <% todos.forEach(item => { %> <li><%= item ...

Tips for validating multiple inputs of the same type with identical names in JavaScript

I have limited experience with Javascript and am facing an issue with a HTML form that contains multiple input types with the same names occurring more than once. My goal is to validate the form before inserting the data into the database. I have managed t ...

Repeated calls to Angular's <img [src]="getImg()"> frequently occur

Can someone help me figure out what's going on here? Recently, I set up a new Angular project and in app.component.html, I have the following code: <img [src]="getDemoImg()"> In app.component.ts: getDemoImg(){ console.log('why so m ...

What is the best way to create a deep clone of an XMLDocument Object using Javascript?

I am currently working on a project that involves parsing an XML file into an XMLDocument object using the browser's implementation of an XML parser, like this: new DOMParser().parseFromString(text,"text/xml"); However, I have encountered a situatio ...

Passing an object in Vue.js during a redirect

i currently have two components named projectListComponent and projectSingleComponent. I want to pass an object from component 1 to component 2 during redirection. Here is my code: projectListComponent.vue <template> <div class="row justify ...

Arrays Filtering without Containing Elements

Is there a utility function in Knockout to filter one array based on another array, or will I need to use JavaScript? First : var obj1 = [{ "visible": "true", "id": 1 }, { "visible": "true", "id": 2 }, { "visible": "true", "id": ...

How to disable the ripple effect of a parent button in Material UI when clicking on a nested child button?

Attempting to nest one button within another (IconButton inside ListItem with the button prop) is proving challenging. The issue lies in the fact that the ripple animation of the ListItem is triggered even when clicking on the IconButton. Ideally, I would ...

Exploring Next.js dynamic imports using object destructuring

import { UDFCompatibleDatafeed } from "./datafeeds/udf/src/udf-compatible-datafeed.js"; I'm facing a challenge in converting the above import to a dynamic import in Next.js. My attempt was as follows: const UDFCompatibleDatafeed = dynamic(( ...