Good day, I'm learning d3.js. I'm reading this candlestick-chart example: https://observablehq.com/@d3/candlestick-chart but its code confused me besause of its first part:
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);
svg.append("g")
.call(xAxis);
svg.append("g")
.call(yAxis);
const g = svg.append("g")
.attr("stroke-linecap", "round")
.attr("stroke", "black")
.selectAll("g")
.data(data)
.join("g")
.attr("transform", d => `translate(${x(d.date)},0)`);
g.append("line")
.attr("y1", d => y(d.low))
.attr("y2", d => y(d.high));
g.append("line")
.attr("y1", d => y(d.open))
.attr("y2", d => y(d.close))
.attr("stroke-width", x.bandwidth())
.attr("stroke", d => d.open > d.close ? d3.schemeSet1[0]
: d.close > d.open ? d3.schemeSet1[2]
: d3.schemeSet1[8]);
g.append("title")
.text(d => `${formatDate(d.date)}
Open: ${formatValue(d.open)}
Close: ${formatValue(d.close)} (${formatChange(d.open, d.close)})
Low: ${formatValue(d.low)}
High: ${formatValue(d.high)}`);
return svg.node();
}
Why did this example put the codes inside chart? What does the svg.node()
do in this example? Thank you!
That's not valid JavaScript, but an example of a "cell" in Observable's custom language (which is built on JavaScript):
https://observablehq.com/@observablehq/observables-not-javascript
You can compare it to a normal function
, but as a bonus, things that depend on each other are automatically recalculated when needed:
https://observablehq.com/@observablehq/how-observable-runs
So in this case, chart
is a "function" that creates a chart based on some data
and other settings, and then returns the SVG element ( svg.node()
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.