d3.select(this)不能用箭頭函式
阿新 • • 發佈:2018-11-10
d3中典型的資料繫結片段
const items = svg.selectAll('g') .data(gdfs,(d)=> d.name); const enter = items.enter().append('g'); //console.log(enter); //沒有update()函數了,新增刪除後,全部更新 enter.merge(items) .attr('class',(d)=> d.name) .each(function(d) { const g= d3.select(this); console.log('g',g); //do some with g; }); items.exit().remove(); }
對g元素如果需要進一步繫結資料進行操作,則呼叫each 傳入匿名函式。 裡面使用d3.select(this) ,這個d3 選擇集,指向each對應的dom元素。
在這裡,要注意this的問題。如果使用es6的箭頭函式() =>{} ,會報錯,必須使用傳統的funcion(d){}
區別在這裡,箭頭函式不繫結this https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions
不繫結
this
在箭頭函數出現之前,每個新定義的函式都有它自己的
this
值箭頭函式不會建立自己的
this,它只會從自己的作用域鏈的上一層繼承this
。
但是d3這裡,顯然是依賴區域性的this的,用箭頭函式,是找上一層的this,會報錯。
——總之,用d3.select(this)的地方,就用傳統的function就好了。反正也不是很多。