"Uncaught ReferenceError: DOM is not defined"

"Uncaught ReferenceError: DOM is not defined"

我理解这行 D3 代码将 SVG 元素添加到 HTML 页面的主体,并将对新元素的引用存储在变量 'svg':

var svg = d3.select('body').append('svg').attr('width', 500).attr('height', 50);

例如,Scott Murray 的书 Interactive Data Visualization for the Web,第 2 版 here 中使用了它。最近我看到了这种模式:

const svg = d3.select(DOM.svg(500, 50));

(例如 this example or this tutorial)。

我想弄清楚这一行的作用,但是当我将它包含在我的脚本中时,我收到了控制台错误

Uncaught ReferenceError: DOM is not defined

我错过了什么?我已经通读了 Scott Murray 的书和​​ D3 选择文档(here) but I cannot find the DOM.svg stuff. (Google 也没什么帮助。)

这既不是标准 Javascript 对象也不是 D3 方法。那是 Observable method.

如果您查看 introduction,您会发现 DOM 是函数的集合:

Object {
  canvas: ƒ(e, t)
  context2d: ƒ(e, t, n)
  download: ƒ(…)
  element: ƒ(e, t)
  input: ƒ(e)
  range: ƒ(e, t, n)
  select: ƒ(e)
  svg: ƒ(e, t)
  text: ƒ(e)
  uid: ƒ(e)
}

所以,在 Observable notebook 中,可以做...

DOM.text("I am a text node.")

...创建一个文本节点,或者,正如您刚刚发现的那样,

DOM.svg(500, 50)

...创建 SVG。但是,这仅适用于 Observable notebook。

为了扩展之前的答案,DOM 确实是 Observable 中标准库的一部分。您可以通过导出或嵌入笔记本在 Observable 之外使用它和其他标准库方法,如 Downloading and Embedding Notebooks 文档页面中所述。