触发 onclick 事件,但未执行附加代码
Onclick event fires, but append-code is not executed
在下面的代码中,触发了 onclick 事件,但没有附加圆圈。我不知道为什么。
可能是因为以下可变因素?
代码片段:
.on("click", function (event, d) {
let center = pathMap.centroid(d.geometry);
console.log(center);
mouse
.append("circle")
.attr("cx", center[0])
.attr("cy", center[1])
.attr("r", 20)
.attr("fill", "red");
mutable selected = d.properties;
来源:https://observablehq.com/@statistikzh/leerwohnungszahlung
在您的笔记本中,每次单击地图中的某个区域时,都会重新评估地图单元格并重新绘制整个地图。正在添加圆圈,但地图立即从头开始重新绘制。
如果你注释掉这些行
console.log(colorScaleOrd(d.properties.GDE_ID));
d3.select(this).style("stroke", colorScaleOrd(d.properties.GDE_ID));
然后您会看到圆圈已添加。
点击处理程序更改 gem_sel
。 colorScaleOrd
依赖于 gem_sel
而地图依赖于 colorScaleOrd
。单击处理程序更新 gem_sel
,这会导致 colorScaleOrd
的单元格被重新计算,从而导致绘制地图的单元格被重新计算。有一种循环依赖。
要引用 Introduction to Mutable State notebook,您应该尽量避免在 Observable 上使用可变状态以防止此类问题。
Note: The mutable
keyword is easy to misuse in a way that makes it more difficult to successfully write Observable notebooks! Think of it as an escape hatch for those rare cases where you find the need to bypass Observable’s reactive dataflow model.
编辑:我创建了一个 fork of your notebook 来演示一种不使用 mutable
.
构建此可视化的方法
在下面的代码中,触发了 onclick 事件,但没有附加圆圈。我不知道为什么。
可能是因为以下可变因素?
代码片段:
.on("click", function (event, d) {
let center = pathMap.centroid(d.geometry);
console.log(center);
mouse
.append("circle")
.attr("cx", center[0])
.attr("cy", center[1])
.attr("r", 20)
.attr("fill", "red");
mutable selected = d.properties;
来源:https://observablehq.com/@statistikzh/leerwohnungszahlung
在您的笔记本中,每次单击地图中的某个区域时,都会重新评估地图单元格并重新绘制整个地图。正在添加圆圈,但地图立即从头开始重新绘制。
如果你注释掉这些行
console.log(colorScaleOrd(d.properties.GDE_ID));
d3.select(this).style("stroke", colorScaleOrd(d.properties.GDE_ID));
然后您会看到圆圈已添加。
点击处理程序更改 gem_sel
。 colorScaleOrd
依赖于 gem_sel
而地图依赖于 colorScaleOrd
。单击处理程序更新 gem_sel
,这会导致 colorScaleOrd
的单元格被重新计算,从而导致绘制地图的单元格被重新计算。有一种循环依赖。
要引用 Introduction to Mutable State notebook,您应该尽量避免在 Observable 上使用可变状态以防止此类问题。
Note: The
mutable
keyword is easy to misuse in a way that makes it more difficult to successfully write Observable notebooks! Think of it as an escape hatch for those rare cases where you find the need to bypass Observable’s reactive dataflow model.
编辑:我创建了一个 fork of your notebook 来演示一种不使用 mutable
.