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.
If you declare the variables outside your functions and then assign to them (without using the
varkeyword in the function) then your functions will be closures, granted access to set and get values from those variables.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:
Note that in this case you cannot unregister
onclicklater because that was not the function that was registered with the handler.