Q:

How to share scope between functions in d3.js?

I'm not sure if this is a d3.js question or a javascript visibility question. I have two functions that assign the same event listener to different nodes:
function render_line(){
    var x = d3.scale.ordinal();
    ...

    d3.select("#my_line").on("click", onclick);
}

function render_bar(){
    var y= d3.scale.linear();
    ...

    d3.select("#my_bar").on("click", onclick);
}

function onclick(d,i){
    use(x,y) // error: can't access x or y
    ...
}

I think it makes sense for both render_line() and render_bar() to share the same event listener function because clicking on one should also update the other but I don't know how the solve the variable scope issue.

A:

If you declare the variables outside your functions and then assign to them (without using the var keyword in the function) then your functions will be closures, granted access to set and get values from those variables.
var x,y;
function foo(){
  x = d3.scale.ordinal();
  d3.select("...").on("click",onclick);
}
function bar(){
  y = d3.scale.linear();
  d3.select("...").on("click",onclick);
}
function onclick(){
  // has access to both x and y here
}

Alternatively, if that's too dirty feeling, then create a closure around the local variable during event registration, passing the value to your shared function:
function foo(){
  var x = d3.scale.ordinal();
  d3.select("...").on("click",function(evt){
    onclick.call(this,evt,x);
  });
}
function foo(){
  var y = d3.scale.linear();
  d3.select("...").on("click",function(evt){
    onclick.call(this,evt,y);
  });
}
function onclick(evt,scale){
  // Use 'scale' passed in
}

Note that in this case you cannot unregister onclick later because that was not the function that was registered with the handler.

