2016-09-29 35 views
1

我正在嘗試創建一個非常基本的面向對象的結構來創建D3圖表。這裏是code轉換爲SVGAnimatedLenght的號碼

沒有類和函數,相同的代碼工作正常,並構建圖表。但是,如果按照上述方式組織,則this.widththis.height的值會轉換爲SVGAnimatedLength,因此我無法對它們執行正常操作(例如this.height - yScale(x))。

我注意到,this.widththis.height只是在遇到添加列的代碼之前保持數字。

this.chart.selectAll(".bar") ... 

要重現,如果你把一個斷點和調試上述變量,它們顯示爲數字,直到上面的代碼(38行)執行。然後突然,他們變成了SVGAnimatedLength

任何幫助表示讚賞。謝謝。

回答

2

this的值在函數內發生了變化。

所以不是在第38行做:

this.chart.selectAll(".bar") 
      .data(this.data) 
      .enter().append("rect") 
      .attr("class", "bar") 
      .attr("x", function(d) { return xScale(d.letter); }) 
      .attr("width", xScale.rangeBand()) 
      .attr("y", function(d) { return yScale(d.frequency); }) 
      .attr("height", function(d) { 
       return this.height - yScale(d.frequency);//value of this is diffrent. 
      }); 

這樣做:

var me = this;//store the value of this in me. 
     this.chart.selectAll(".bar") 
      .data(this.data) 
      .enter().append("rect") 
      .attr("class", "bar") 
      .attr("x", function(d) { return xScale(d.letter); }) 
      .attr("width", xScale.rangeBand()) 
      .attr("y", function(d) { return yScale(d.frequency); }) 
      .attr("height", function(d) { 
       return me.height - yScale(d.frequency);//use me variable 
      }); 
    } 
} 

工作代碼here

+0

感謝解釋。 – akshayKhot