如何使用coffeescript使用“this”和“this”(胖箭头)?

如何使用coffeescript使用“this”和“this”(胖箭头)?,coffeescript,d3.js,Coffeescript,D3.js,我正在使用D3函数each,它接受回调函数并将其作为参数传递this,但我需要访问this和\u this。这是coffeescript代码: @x = d3.scale.ordinal().domain(d3.range(@model.geneExpressions[0].length)).rangeBands([0, width]) getRow = (row) => cell = d3.select(this).selectAll(".cell")

我正在使用D3函数
each
,它接受回调函数并将其作为参数传递
this
,但我需要访问
this
\u this
。这是coffeescript代码:

@x = d3.scale.ordinal().domain(d3.range(@model.geneExpressions[0].length)).rangeBands([0, width])    

getRow = (row) =>
    cell = d3.select(this).selectAll(".cell")
        .data(row)
      .enter().append("rect")
        .attr("x", (d,i) => @x(i))    

rows = @heatmap.selectAll(".row")
    .data(@model.geneExpressions)
  .enter().append("g")
    .each(getRow)                    
以及它生成的javascript:

    var _this = this;    

this.x = d3.scale.ordinal().domain(d3.range(this.model.geneExpressions[0].length)).rangeBands([0, width]);    

getRow = function(row) {
        var cell;
        return cell = d3.select(_this).selectAll(".cell").data(row).enter().append("rect").attr("x", function(d, i) {
          return _this.x(i);
        })
      };    

rows = this.heatmap.selectAll(".row").data(this.model.geneExpressions).enter().append("g").attr("class", "row").each(getRow);
我怎样才能让coffeescript在这行中使用
this
,并保持一切不变

return cell = d3.select(this) ...

问题是,我不能将@x作为参数传递给
每个
并使用细箭头而不是胖箭头(因为那样我就无法访问@x),除非我重写了D3函数,这似乎有些过分

所以你有这个结构:

@x = ...
getRow = (row) =>
    d3.select(@)...attr('x', (d, i) => @x(i))
rows = ...each(getRow)
但是您需要
getRow
成为一个普通的
->
函数,这样它就可以将DOM元素作为
@
获取,并且需要
attr
回调成为一个绑定的
=>
函数,这样
@x
就可以工作了,对吗

我立刻想到两种可能性:

  • 使用普通JavaScript
    var的CoffeeScript形式,即=this技巧
  • attr
    回调使用命名绑定函数
  • 第一个看起来像这样:

    that   = @
    getRow = (row) ->
        cell = d3.select(@)
            .selectAll(".cell")
            .data(row)
            .enter().append("rect")
            .attr("x", (d,i) -> that.x(i))    
    
    x_at_i = (d, i) => @x(i)
    getRow = (row) ->
        cell = d3.select(@)
            .selectAll(".cell")
            .data(row)
            .enter().append("rect")
            .attr("x", x_at_i)
    
    第二个是这样的:

    that   = @
    getRow = (row) ->
        cell = d3.select(@)
            .selectAll(".cell")
            .data(row)
            .enter().append("rect")
            .attr("x", (d,i) -> that.x(i))    
    
    x_at_i = (d, i) => @x(i)
    getRow = (row) ->
        cell = d3.select(@)
            .selectAll(".cell")
            .data(row)
            .enter().append("rect")
            .attr("x", x_at_i)