简体   繁体   中英

d3.js dynamically create brush functions

My 'fixed length' example works well.

I currently have an array of brushes (that I use for histograms) for which I define in an array:

var brushFunctionArray = [brush0,brush1,brush2];

I go through a histogram loop to create the histograms and for each brush I use:

var brush = d3.svg.brush()
                .x(x)
                .on("brush", brushFunctionArray[i]);

And I define the brushes like so:

function brush0 () {brushmove(0);}
function brush1 () {brushmove(1);} 
function brush2 () {brushmove(2);} 

Then have one definition for brushmove:

function brushmove(index){ 
    ...
    ...
}

This works fine. BUT, I want to be able to make the array at run time to move beyond the fixed length(brush0 ... brushB). I have tried to create the functions dynamically:

var brushFunctionArray = [];

for (var i = 0; i < numOfHistograms; i++){
    var func = new Function("return function brush" + i + "  () {brushmove("+i+");}")();
    brushFunctionArray.push(func);
}

This creates the functions and inserts them into the array but I can't quite use the brushFunctionArray in the .on("brush",..) like before because the functions are in there and not the names of the functions. Plus when I put the functions in the array I no longer initialize them.

Thanks for any suggestions!

You should be able to use them as you want by inserting anonymous (ie unnamed) functions into your array.

var brushFunctionArray = [];
for (var i = 0; i < numOfHistograms; i++){
  brushFunctionArray.push(function() { brushmove(i); });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM