1

I am following Mike Bostock's pattern for reusable charts - closures with getter/setters. But somehow, when I instantiate a new chart object with new properties, existing charts are being updated with these properties:

var chart1 = new StackedAreaChart();
d3.select('#chart1')
    .data([data])
    .call(chart1);     

// a new chart - whose properties end up in chart1!
var chart2 = new StackedAreaChart().colors(['green', 'blue']);

Here's an example: http://jsfiddle.net/samselikoff/YZ6Ea/3/. Resize the window to see the first chart re-rendered, with a stylish but unexpected green tint.

I am baffled by this. I suspect (1) my setter is mutating the actual 'constructor', and (2) somehow chart1 is really a reference to this constructor, rather than being a separate instance of it like I thought.

I was thinking of using this.margin = ... instead of var margin =, but since this is the suggested pattern I wanted to post here first. What am I missing?

Sam Selikoff
  • 11,238
  • 9
  • 54
  • 94

1 Answers1

1

If you are following Mike's tutorial, you shouldn't be using new when creating the chart:

var chart1 = StackedAreaChart();

d3.select('#chart1')
  .data([data])
  .call(chart1);

StackedAreaChart will return a function, and that function will be called once for each element in the selection when the data is binded.

Pablo Navarro
  • 7,924
  • 2
  • 38
  • 51
  • Even without `new`, the problem is still there. http://jsfiddle.net/samselikoff/YZ6Ea/4/ – Sam Selikoff Jun 06 '13 at 16:29
  • 2
    You missed a semicolon in the declaration of variables for `StackedAreaChart`, that transformed the chart variables in global variables (`xScale`, `yScale`, etc). The updated fiddle is here: http://jsfiddle.net/pnavarrc/YZ6Ea/5/ – Pablo Navarro Jun 06 '13 at 17:53
  • 1
    You can avoid that kind of mistakes using a linter, like http://www.jshint.com. You will polish your code and learn best practices at the same time. – Pablo Navarro Jun 06 '13 at 18:14
  • Thanks. Btw, what's the difference between using or not using `new`? – Sam Selikoff Jun 06 '13 at 18:17
  • Here: http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript – Pablo Navarro Jun 06 '13 at 18:36