In this example: https://observablehq.com/@d3/connected-scatterplot
The first block of code begins like this:
chart = {
replay;
//...create svg element and setup the chart...
return svg.node();
}
Two questions (I apologize if these are simple but I'm new to javascript and google is not availing me anything):
1) chart looks like a function since it has a return statement, but there is no function keyword. If I try something like this for myself in my flask application, I get errors when I put a return statement because it is being evaluated as an object definition? Is this some node.js thing?
2) What is that line "replay;" doing? I don't see any references to it elsewhere in the code
Edit: I found the answer here: https://observablehq.com/@observablehq/observables-not-javascript
In short, anything on that website is not-quite-javascript, which is really confusing when learning D3.js and almost all the examples are on that website (and the above page is somewhat difficult to find). But I guess that's all part of the business model to get people to subscribe and develop on observablehq rather than writing standalone web apps.
I work for Observable, and yeah, “Observable’s not JavaScript” is the best thing to read on that. chart
is declaring a reactive variable; it uses no keyword; it can be defined as a single expression, like x = d3.scaleLinear()
, or as a curly-braces function block that returns a value, as you saw. You can download the notebook compiled into plain JavaScript by clicking “Download code” in the “⋯” menu in the upper right; here I’ve annotated the source of a line chart example. You can see there how the cell gets compiled into a normal JavaScript function that’s passed the values of the other cells it depends on. In that “Connected Scatterplot” example, if you download the code, the body of the chart
cell ends up looking like this:
function(replay, d3, width, height, length, line, data, xAxis, yAxis, x, y, halo) {
replay;
//...create svg element and setup the chart...
return svg.node();
}
The way reactivity works is that each cell is re-evaluated whenever one of the cells it refers to changes. The replay;
line takes advantage of that to redraw the scatterplot when you click the button, which fires its click event, which triggers the reactive re-evaluation, even though it’s not passing any data or being assigned to a variable or anything.
(I suppose it is a business, but we’re really trying to make coding these things easier! Happy to chat if you have questions.)