Callback for Variable Change

Is there a way to have a function trigger when a variable changes its value? In the code snippet provided, there is a function called loadImage that fetches the image material. However, if this code is executed, the declaration of mesh and scene.add(mesh) will occur before the image is fully loaded. Is there a method to ensure that the variable finishes loading before proceeding with other commands? Thank you for your help! ^u^


var geometry = new THREE.BoxGeometry(1, 1, 1);
var materialimg = new THREE.MeshBasicMaterial();
var materialimg = loadImage("test/map.jpg", manager);
var mesh = new THREE.Mesh(geometry, materialimg);
scene.add(mesh);

Here is the defined LoadImage function:


function loadImage(imagePath, loadingManager){
    var loader = new THREE.ImageLoader(loadingManager);

    // Create a texture
    var texture = new THREE.Texture();

    loader.load(imagePath, function(image){
        texture.image = image;
        texture.needsUpdate = true;
        var material = new THREE.MeshBasicMaterial();
        material.map = texture;

        return material;
    });   
} 

This is how the testImage function, which calls the LoadImage function, looks like:


function testImage(){
    var manager = new THREE.LoadingManager();
    manager.onProgress = function(item, loaded, total){
        console.log(item, loaded, total);
    }

    var geometry = new THREE.BoxGeometry(1, 1, 1);
    var materialimg = new THREE.MeshBasicMaterial();
    var materialimg = loadImage("test/map.jpg", manager);

    var mesh = new THREE.Mesh(geometry, materialimg);
    scene.add(mesh);
}

Answer №1

To incorporate a callback function, consider the following approach:

function fetchImage(imagePath, manager){
    var loader = new THREE.ImageLoader(manager);

    //initialize a texture
    var texture = new THREE.Texture();

    loader.load(imagePath, function(image){
        texture.image = image;
        texture.needsUpdate = true;
    });   

    return new THREE.MeshBasicMaterial({ map: texture, overdraw: true });
} 

function checkImage(){
    var loadingManager = new THREE.LoadingManager();
    loadingManager.onProgress = function(item, loaded, total){
        console.log(item, loaded, total);
    }

    var geometry = new THREE.BoxGeometry(1, 1, 1);
    var materialImg = fetchImage("sample/image.jpg", loadingManager);

    var mesh = new THREE.Mesh(geometry, materialImg);
    scene.add(mesh);
}

UPDATE: The above code has been revised to address using return in a callback function within a different 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

Unbinding or undoing an 'onclick' event when another 'onclick' event is triggered

I am facing an issue where clicking on elements with 'onclick' functions works as expected, but when I click on a different element with another 'onclick' function, the first one remains active. What I actually want is for the previous ...

What could be causing the `unstable_Profiler` to not function properly in production mode?

Encountering a problem with unstable_Profiler in my React-Native project where the onRender callback is being ignored, but only in production mode. No errors are being thrown and everything renders correctly. I followed the advice from this article: I tes ...

Loading content synchronously

Could you assist me in finding a solution to synchronize the loading of pages and elements? Currently, my code looks like this: $(Element).load(File); ... other commands... window.onload = function () { Update_Elements(Class, Content); } Everything ...

Is there a way to prevent undefined properties when using .each in jQuery with a JSON object?

I am trying to populate the values of <inputs> on a webpage using data from a JSON object. http://codepen.io/jimmykup/pen/exAip?editors=101 To begin, I create a JSON object with two values - one for name and one for url. var jsonObj = []; var nam ...

"Can anyone provide guidance on how to initiate a css 3d animation by clicking a button

Currently, I am developing a folding hide/show animation that can be triggered using Javascript. If you would like to take a look at the code and see a working example, please visit this link: You can also view just the gist here: https://gist.github.com ...

Uploading files in AngularJS using Rails Paperclip

I have been working on implementing a file upload feature with AngularJS/Rails using the Paperclip gem. I was able to resolve the file input issue with a directive, but now I am facing an issue where the image data is not being sent along with other post d ...

Animating an image inside a bordered div

I'm attempting to create an animated effect where an image moves randomly within the boundaries of a div container. While I've come across solutions for animating within borders, none have specifically addressed keeping the image inside the div. ...

Vue snapshot testing is encountering a failure with the error message "TypeError: Cannot read property of undefined"

Everything seems to be working fine with the component on the page without any errors. Storybook is also functioning well, but the problem lies in the unit test. import { mount } from '../../vue'; import { createLocalVue } from '@vue/test-u ...

Adjust the size of an image and move its position both vertically and horizontally using Javascript

I am currently working on transforming an image both vertically and horizontally, as well as scaling it using JavaScript. While I have managed to resize the image successfully, it doesn't quite look how I want it to. I am aiming for a similar effect a ...

Modifying text on input buttons using Javascript

Including product names, text forms, and buttons on a webpage is essential for showcasing products effectively. Each product is assigned an ID such as p1, p2, etc., while the input types are identified by i1, i2, etc. When users enter information into the ...

Processing two Array Objects can be achieved without resorting to the EVAL function

I have two objects that I need to process. obj1 contains an array of objects with formulas. obj2 holds the values needed for the calculations. I am looking for a way to process and calculate both objects in order to obtain a result where the keys present ...

Filter out the selection choice that begins with 'aa' in the drop-down menu

Here is a select field with various options: <select id="sel"> <option value="1">aadkdo</option> <option value="2">sdsdf</option> <option value="3">aasdfsddkdo</option> <option value="4"> ...

Is it possible to reference and assign controllers from templates in Angular 2 like in previous versions?

In my opinion, one of the great things about Angular 1 is that developers can write business logic in controllers without having to reference anything related to markup or rendering. After reading the Angular 2 documentation, I came across this code snipp ...

Looping through elements using .each in jQuery and accessing their values in the following iteration

Here is the code snippet I've been working on: var index=0; var load=0; $("td.load_ads").each(function(){ var loading=$(this); $.post('/self_coded_helpers/jpost_get_ads.php',{index:index,type:'fetch_id' ...

I encounter a CORS issue on Heroku, but strangely it only occurs after 20 minutes of deploying. Prior to that time frame, everything functions seamlessly

Today, I encountered a strange issue while hosting my first Node JS backend on Heroku. Everything runs smoothly when I register/login immediately after deploying the backend. However, if I try to register/login after about 15 minutes, I start receiving a C ...

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 ...

Utilizing AngularJS to iterate over a single extensive unordered list

In my current Angular app, the JSON structure is as follows: 0: Object $$hashKey: "004" Date: "2014-04-17" Items: Array[3] 1: Object $$hashKey: "005" Date: "2014-04-18" Items: Array[3] 2: Object $$hashKey: "006" ...

Save an automatically generated number into a variable and use it to reference an image file for display. This process can be accomplished using JavaScript

I'm having trouble getting my images to display randomly on a page. The images are named 0 - 9.png and I am using a pre-made function for random number generation. However, when I try to call on this function later down the page, nothing appears. It ...

Adjust the href link value when a new option is selected

I currently have a select element displayed below. Next to it, there is a link that sets the eID value to a session value. However, I want this value to be updated dynamically whenever a different eID value is selected from the dropdown. Although I can r ...

Safari Glitch in Bootstrap 4

For a simplified version, you can check it out here: https://jsfiddle.net/dkmsuhL3/ <html xmlns="http://www.w3.org/1999/xhtml"> <title>Testing Bootstrap Bug</title> <!-- Bootstrap V4 --> <link rel="stylesheet" href="https://m ...