Passing additional parameter to loaded_cb (callback)

16 October 2016 12:22

This is more a JavaScript issue than a Blend4Web API issue. Nonetheless, it's something I'm struggling with so if anyone can provide some insight that would be great :)

The problem: I'm dynamically loading (child) scenes into a (parent) scene using the m_data.load function ( This function includes an optional callback function (loaded_cb) to be executed right after load. I need to pass an additional parameter to this loaded_cb callback function.

My understanding is that this (in JavaScript) is normally accomplished with either a closure or with "bind" ( I have tried both approaches but I'm just not getting it right.

I've searched on Stack Overflow for possible solutions and these are the kind of suggestions that come up:
1 -
2 -

So, I get a list of (child) scenes to load into the (parent) scene from a web service. I loop over the list, get the reference to the resource path, load it, and then (in theory) position it accordingly (the position information is also retrieved from the web service for each child scene). It is this "position" information that I need to pass to the loaded_cb callback function (code snippet, below):

// Load and position props (including rotation and scaling).
var props = sceneDefinition.scene.entities.props;
props.forEach(function(prop) {
    position = JSON.parse(prop.location);
    m_data.load(APP_ASSETS_PATH + getEntityScene(prop), entityLoaded, preloader_cb, true, true);

In my case, the "entityLoaded" function is the (cb_loaded) callback that I need to be passing in the position parameter. Currently, I am using a global (position), which works if there is only one child scene, but with more child scenes, the "position" variable is not appropriately updated for each iteration in the loop when eventually the callback is executed. So, I need to "lock" the position parameter to the appropriate execution context of the callback.

If anyone can help with this matter it will be greatly appreciated :)

17 October 2016 12:39
Hi, Brett! You can use an object to store the positions for the loaded scenes. m_data.load returns an id of a scene that can be used as a key. Also this id is available as the first parameter in the "loaded_cb" callback:

var positions = {}

var props = sceneDefinition.scene.entities.props;
props.forEach(function(prop) {
    var data_id = m_data.load(APP_ASSETS_PATH + getEntityScene(prop), entityLoaded, preloader_cb, true, true);
    positions[data_id] = JSON.parse(prop.location);

function entityLoaded(data_id, success) {
    var pos = positions[data_id];
17 October 2016 20:54
That worked! Thanks Ivan.


Please register or log in to leave a reply.