局部变量
🌐 Local variables
D3 本地变量允许你定义独立于数据的本地状态。例如,在渲染时间序列数据的小倍数图时,你可能希望所有图表使用相同的 x 轴比例,但使用不同的 y 轴比例以比较各指标的相对表现。D3 本地变量以 DOM 元素为作用域:在设置时,值存储在指定元素上;在获取时,值从指定元素或最近定义该值的祖级元素中检索。
🌐 D3 locals allow you to define local state independent of data. For instance, when rendering small multiples of time-series data, you might want the same x scale for all charts but distinct y scales to compare the relative performance of each metric. D3 locals are scoped by DOM elements: on set, the value is stored on the given element; on get, the value is retrieved from given element or the nearest ancestor that defines it.
小心
本地变量很少使用;你可能会发现将所需的任何状态存储在选区的数据中更容易。
local()
来源 · 声明一个新的局部变量。
const foo = d3.local();像 var 一样,每个 local 都是一个独立的符号引用;不像 var,每个 local 的值也由 DOM 作用域控制。
🌐 Like var, each local is a distinct symbolic reference; unlike var, the value of each local is also scoped by the DOM.
local.set(node, value)
来源 · 将此本地变量在指定的节点上设置为值,并返回指定的值。这通常使用selection.each 执行:
selection.each(function(d) {
foo.set(this, d.value);
});如果你只是设置一个单独的变量,请考虑使用 selection.property:
🌐 If you are just setting a single variable, consider using selection.property:
selection.property(foo, (d) => d.value);local.get(node)
来源 · 返回指定 节点 上此本地变量的值。
selection.each(function() {
const value = foo.get(this);
});如果节点没有定义此本地变量,则返回最近的定义它的祖级的值。如果没有祖级定义此本地变量,则返回未定义。
🌐 If the node does not define this local, returns the value from the nearest ancestor that defines it. Returns undefined if no ancestor defines this local.
local.remove(node)
Source · 从指定的 node 中删除此本地的值。
selection.each(function() {
foo.remove(this);
});如果在移除之前该 节点 定义了此局部变量,则返回 true,否则返回 false。如果祖级也定义了此局部变量,这些定义不受影响,因此 local.get 仍将返回继承的值。
🌐 Returns true if the node defined this local prior to removal, and false otherwise. If ancestors also define this local, those definitions are unaffected, and thus local.get will still return the inherited value.
local.toString()
来源 · 返回此本地变量的自动生成标识符。这是用于在元素上存储本地变量值的属性名称,因此你也可以使用 element[local] 或通过 selection.property 设置或获取本地变量的值。