2015-10-01 113 views
14

可能嗎?我不確定,因爲D3大量使用this重寫,這似乎與ES6 spec相沖突。在d3上使用箭頭功能

例如,以下工作正常:

// Working fine 
var data = [1,2,3] 
var svg = d3.select('body').append('svg').attr('height', 500).attr('width', 500).style('background-color', 'orange'); 
var gs = svg.selectAll('g').data(data).enter(); 
gs.append('circle') 
    .attr('cx', function() { return Math.random()*500; }) 
    .attr('cy', function() { return Math.random()*500; }) 
    .attr('r', function() { return Math.random()*100; }) 
    .each(function() { console.log(this); }); // this is bound to the current element in the enter selection 

雖然以下不按預期工作(this未綁定到當前元素的輸入選擇,但到Window對象):

var data = [1,2,3] 
var svg = d3.select('body').append('svg').attr('height', 500).attr('width', 500).style('background-color', 'blue'); 
var gs = svg.selectAll('g').data(data).enter(); 
gs.append('circle') 
    .attr('cx',() => Math.random()*500) 
    .attr('cy',() => Math.random()*500) 
    .attr('r',() => Math.random()*100) 
    .each(() => console.log(this)); // this is bound to Window object 

相關小提琴here

+1

@chriskelly你的例子只是設置在選擇的所有元素的值相同,那不是我想要實現(什麼這就是爲什麼函數用於每個元素的原因) – jarandaf

+1

當我運行您的示例時,我看到的唯一區別是輸出控制檯日誌。但你爲什麼要訪問'''這個'''。這是一個有趣的問題,但我想知道這是一個問題。 – chriskelly

+0

@chriskelly它是一個非常具體的用例(有一些我想要重用的函數,它在svg組中創建了一個複雜的元素結構,我需要'this'來知道我引用的是哪個組,其中將添加新元素)。 – jarandaf

回答

8

如果您不需要訪問當前元素的this,則可以使用箭頭函數。

在您想要訪問當前元素的this的情況下回退到舊樣式函數。

或者使用顯式綁定,讓你的功能(不箭頭功能)訪問的任何對象,你想使用.bind()

爲了避免與this你必須使用D3名稱或類選擇的選項,以方便地訪問工作任何元素。例如:

var stuffINeed = svg.selectAll('.someClass'); 
2

無法修改箭頭函數的行爲。它們的綁定是'硬編碼',不能通過與bind方法重新綁定或通過調用接受顯式執行上下文的任何其他函數方法(例如apply)來更改。同樣可以說任何綁定函數 - 一旦綁定,返回的函數永遠綁定

這可能嗎?

根據以上考慮,如果D3採用bind ING提供便捷的鏈接行爲,這不能使用箭頭功能,直到D3的API以某種方式,以適應他們修改實現

5

如果您正在使用d3v4,您可以訪問當前的DOM節點是這樣的:

gs.append('circle') 
    .attr('cx',() => Math.random()*500) 
    .attr('cy',() => Math.random()*500) 
    .attr('r',() => Math.random()*100) 
    .each((d, i, j) => console.log(j[i])); 
     // j is current group, i is current index