2017-01-25 33 views
0

我有一個d3圖表,用戶可以沿着y軸拖動一些點。如何確保數據在d3上正確傳遞?

我想要做的是更新原始數據數組,以包括該圖表上表示的任何值的用戶更新選項。

這裏是拖動功能:

function dragged(e) { 
      let yLocation = d3.event.y; 

      let index; 
      for (index = 0; index < data.length && data[ index ][ 'x' ] !== e.x; index++) { 
      } 
      data[ index ][ 'y' ] = (y.invert(d3.mouse(this)[ 1 ])); 

      d3.select(this).select("circle") 
       .attr("cy", e.y = yLocation); 

      update(data); 
     } 

我的問題是試圖更新數組中的值時:如果我嘗試

data[ index ][ 'y' ] = (y.invert(d3.mouse(this)[ 1 ])); 

和日誌(y.invert(d3.mouse(this)[ 1 ])),正確的值(對應的值到鼠標的位置)顯示,但是如果我嘗試記錄數據數組,該對象更新與鼠標的位置,而不是對應於該位置的值。

在更新對象數組之前,我應該使用promise來控制值嗎?還是有更好的解決方案? 謝謝。

回答

1

什麼是你試圖與這行做的事:

d3.select(this).select("circle") 
.attr("cy", e.y = yLocation); 

e這裏是數組中的數據對象。通過將e.y設置爲yLocation,您正在將陣列基準的y值更新爲鼠標位置。 還記得,當你傳遞一個JavaScript對象到一個函數中時,它是一個參考到對象(​​意思是它是同一個對象)。這意味着你不需要搜索和更新你的數據數組,你已經擁有了你想要的部分!

正確的代碼在這裏(未經測試,當然)是:

let yLocation = d3.event.y; 
e.y = y.invert(d3.mouse(this)[ 1 ]); 
d3.select(this).select("circle") 
    .attr("cy", yLocation); 
+0

你,先生,是一個傳奇! :) 謝謝! – abedzantout