0

How correct pass parameters to static function with RequireJS? Below I need run function render and pass to this function two parameters "node" and "bus".

var nodes = document.querySelectorAll('*[ondrawjs]');
var node;
for(var i = 0; node = nodes[i]; i++) {
    var render_name =  node.getAttribute('ondrawjs');           
    require(['agera/' + render_name], function(module) {
        module.render(node, bus);
    });         
}
try-catch-finally
  • 7,436
  • 6
  • 46
  • 67

1 Answers1

1

Note that the RequireJS callback is called async.

Your node variable is scoped to the surrounding (global) context and will have the latest value it was assined to during the loop. When the callback is called, node has the last value.

You need to bind the variable through a closure function:

function makeCallback(node, bus) {
    return function(module) {
        module.render(node, bus);
    };
}

Now the outer node variable is "duplicated" inside makeCallback(), it will remain at its value.

var nodes = document.querySelectorAll('*[ondrawjs]');
var node;

for (var i = 0; node = nodes[i]; i++) {
    var render_name =  node.getAttribute('ondrawjs');
    require(['agera/' + render_name], makeCallback(node, bus));
}

(Note: I assume the missing bus variable is actually present in your code.)

try-catch-finally
  • 7,436
  • 6
  • 46
  • 67