选择.调用是否真的返回 d3 中的选择

Does selection.call really return the selection in d3?

本文关键字:选择 d3 真的 调用 是否 返回      更新时间:2023-09-26

根据文档,selection.call()返回当前选择,但是当我测试它时,我看到了不同的行为。

代码:

var nodeEnter = node.enter().append("g")
                .attr("class", "node")
                .on("click", click)
                .call(force.drag);
    nodeEnter.append("circle")
            .attr("r", function(d) { return Math.sqrt(d.size) / 10 || 4.5; });

应与以下内容相同:

var nodeEnter = node.enter().append("g")
                .attr("class", "node")
                .on("click", click)
                .call(force.drag)
                .append("circle")
                .attr("r", function(d) { return Math.sqrt(d.size) / 10 || 4.5; });

但我看到了不同的行为。这是小提琴。请参阅第 57 - 61 行。使用第二种形式时,节点中的文本消失。

来自 d3 源...

d3_selectionPrototype.call = function(callback) {
  var args = d3_array(arguments);
  callback.apply(args[0] = this, args);
  return this;
};

d3_selectionPrototype被塞在每个选择的__proto__上,所以选择this

你可以追踪它...

d3.select = function(node) {
  var group;
  if (typeof node === "string") {
    group = [d3_select(node, d3_document)];
    group.parentNode = d3_document.documentElement;
  } else {
    group = [node];
    group.parentNode = d3_documentElement(node);
  } 
return d3_selection([group]);
}

function d3_selection(groups) {
  d3_subclass(groups, d3_selectionPrototype);
  return groups;
}

var d3_subclass = {}.__proto__?
// Until ECMAScript supports array subclassing, prototype injection works well.
function(object, prototype) {
  object.__proto__ = prototype;
}:
// And if your browser doesn't support __proto__, we'll use direct extension.
function(object, prototype) {
  for (var property in prototype) object[property] = prototype[property];
};