Reputation: 8847
This is probably a JS question, perhaps more than a D3 question
I have several D3 visualizations on a single page, all being build from the same code. In order to have some kind of namespace, I made a class (well, a function in JS) which I instantiate. Something like the following:
function AlmViz(params) {
...
this.svg = this.chartDiv.append("svg")
.attr("width", this.width + this.margin.left + this.margin.right)
.attr("height", this.height + this.margin.top + this.margin.bottom)
.append("g")
.attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")");
...
}
function loadData(viz) {
...
viz.svg.selectAll(".bar")
.data(level_data)
.enter().append("rect")
...
...
}
// I loop here and call this several times
// with different paramters, so I get a bunch of
// different graphs
var viz = new AlmViz(params);
loadData(viz);
chartDiv.svg.append("a")
.attr("href", "#")
.text("to change click here")
.on("click", change);
I would now like to add some transitions, which requires the use of that .on("click", change). However, the change function, in all the d3 examples, that function is dependent on having access to variables that are in the current scope. How do I get access to the instance of AlmViz that corresponds to the chart that goes with a specific instance?
Note: this has been posted on the d3 Google group, but it didn't seem to be getting much attention there so I'd thought I'd come back to STO. The original post is here: https://groups.google.com/forum/?fromgroups=#!topic/d3-js/1o4mYnMJZTA
Upvotes: 0
Views: 1339
Reputation: 109232
You can pass the current state as an argument to your change function like this:
.on("click", function() { change(viz); });
Upvotes: 2