score:1

Accepted answer

Okay, as suggested by @altocumulus, as public penance I'm posting my own answer :-)

Of course, the documentation is very clear on how to call a function. Just pass the other params :-)

But here, I'll go one step further and create a blueprint for a reusable function that does accept function parameter and also makes use of the function, as I didn't find an example online. Being new to Javascript, I learnt several new things here including apply and arguments.

// Here's my re-usable component

var myown = {};
myown.brush = function(){

  // setup variable
  var height = 0;
  
  function my(group){
    group.each(function(d,i){
      // here is the code for creating brush
      // note `this` is also available (in addition to d and i), for e.g.
      var b = d3.select(this);
      
      console.log("inside my each "+height);
      
    });
  }
  
  my.move = function (group, position){
    console.log("in move function");
    
    group.each(function(d,i){
      // here is the code for moving the brush
      // note `this` is also available (in addition to d and i), for e.g.
      var b = d3.select(this), that = this;
    
      console.log("inside move each");
      console.log(typeof(position));   // note it is function
      
      // now call that function
      // using "apply" and "arguments"
      let pos = position.apply(that, arguments);
      console.log(pos); 
    
    })
    
    return my;
  }
  
  my.height = function(value){
    if(!arguments.length) return value;
    height = +value;
    return my;
  }
  
  return my;
};

// Okay, now use all that nice code

var data = [
  {id: 1, mv: [100,500]},
  {id: 2, mv: [300,600]},
  {id: 3, mv: [800,1000]}
];

var brush = myown.brush().height(90);
    
var svg = d3.select("svg");

var g = svg.selectAll("g").data(data).enter()
  .append("g")
  .attr("transform", (d,i)=>"translate(0,"+i*100+")");
  
g.call(brush).call(brush.move, (d,i)=>d.mv);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width=1500 height=1000></svg>


Related Query

More Query from same tag