2015-06-28 51 views
0

根據文檔selection.call()返回當前的選擇,但是當我測試這個時,我看到不同的行爲。selection.call真的會在d3中返回選擇嗎?

代碼:

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; }); 

但我看到不同的行爲。 Here是小提琴。見第57 - 61行。當使用第二種形式時,節點中的文本消失。

+1

你nodeEnter對象是圓形元素的選擇,不是g元素,所以你不能追加文本元素。 –

+0

Ahhh,沒錯,但從理論上講,在「呼叫」結束時加入代碼仍然有效嗎?我會測試它。 – timebandit

+1

是的,通話返回廣告中的選擇... –

回答

2

從D3源...

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

d3_selectionPrototype被bunged到每一個選擇的__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]; 
}; 
+0

我想我會更多地關注未來源的實際黑暗沼澤。 – timebandit

+2

我推薦它!並不像其他任何東西那樣黑暗,它似乎不可能在一開始,但很快它就會點擊。只需將它放在GIT上,並隨時隨地爲您的叉子添加註釋就是我所做的。 –

+0

優秀的建議! – timebandit