2015-11-18 31 views
2

由於某些原因,d3使用this來指代.each()迭代中的當前元素。如何使用d3的每種方法和ES6箭頭符號

我有這個代碼:

var me = this; 
... 
d3.selectAll(".region").each(function(d) { 
    d3.select(this).style("fill", me.compute_color(...)); 
}) 

隨着ES6,我可以用箭頭標記,以避免覆蓋this

d3.selectAll(".region").each(d => { 
    d3.select(this).style("fill", this.compute_color(...)); 
}) 

但是,此代碼不起作用,因爲D3是選擇錯誤的元素。事實上,我已經失去了對元素的唯一引用,因爲this沒有被d3覆蓋。

如何更改d3.select(this)以使其正常工作?

+0

不是100%肯定,但我認爲你不能在不改變d3.each代碼,如箭頭函數不會選擇由它們的代碼(節點)發送的。因此,對於那些以傳統方式保持傳統方式的案例,我猜想是最好的 – juvian

+0

問題是我從任何地方刪除了舊的'me' ...我不想回滾所有內容 – wil93

+0

嗯,也許你可以自己迭代:d3。 selectAll(「。region」)[0] .forEach(d => { \t d3.select(d).style(「fill」,this.compute_color(...)); })但是這裏d會引用到d3元素而不是數據 – juvian

回答

0

您可以使用作爲第二個參數傳遞的指數從集合訪問正確的元素:

let selection = d3.selectAll(".region"); 
selection.each((d, i) => { 
    d3.select(selection[0][i]).style("fill", this.compute_color(...)); 
})