Skip to content

局部变量

¥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.

CAUTION

局部变量很少使用;你可能会发现,将所需的任何状态存储在选择数据中更容易。

¥Locals are rarely used; you may find it easier to store whatever state you need in the selection’s data.

local()

源代码 · 声明一个新的局部变量。

¥Source · Declares a new local variable.

js
const foo = d3.local();

类似 var,每个局部变量都是一个不同的符号引用;与 var 不同,每个局部变量的值也受 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) {#local_set}

源代码 · 将指定节点上此本地的值设置为指定的值,并返回指定的值。这通常使用 selection.each 执行:

¥Source · Sets the value of this local on the specified node to the value, and returns the specified value. This is often performed using selection.each:

js
selection.each(function(d) {
  foo.set(this, d.value);
});

如果你只设置一个变量,请考虑使用 selection.property

¥If you are just setting a single variable, consider using selection.property:

js
selection.property(foo, (d) => d.value);

local.get(node) {#local_get}

源代码 · 返回指定节点上此局部变量的值。

¥Source · Returns the value of this local on the specified node.

js
selection.each(function() {
  const value = foo.get(this);
});

如果节点未定义此本地节点,则返回定义它的最近祖级节点的值。如果没有祖级节点定义此局部变量,则返回 undefined。

¥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) {#local_remove}

源代码 · 从指定节点删除此局部变量的值。

¥Source · Deletes this local’s value from the specified node.

js
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() {#local_toString}

源代码 · 返回此本地节点的自动生成的标识符。这是用于在元素上存储本地值的属性名称,因此你也可以使用 element[local] 或 selection.property 设置或获取本地值。

¥Source · Returns the automatically-generated identifier for this local. This is the name of the property that is used to store the local’s value on elements, and thus you can also set or get the local’s value using element[local] or by using selection.property.