Search code examples
callbackd3.jscubism.js

Cubism callback array seemingly replaced


I'm using some static data to generate charts using cubism's context.metric function. However, all of the charts end up displaying the same array of values (the last one passed in) although I passed in different arrays in the callback function.

var metrics = [];
for (var key in toGraph) {
    var m = context.metric(function(start, stop, step, callback) {
        callback(null, toGraph[key]);
    }, key);

    metrics.push(m);
}

toGraph is a dictionary with key being the name of each metric and the value being an array of the metric values.

The values ended up being displayed are always the last array of values I pass in.

I couldn't figure out what's wrong. Am I using context.metric wrong or using the callback function wrong? Any help would be greatly appreciated, thank you!


Solution

  • Turns out it was a javascript closure inside loop problem.

    Examples like this and this explained the problem.