0

这可能会在文档中得到解答,但我无法解决。

基本上我有一些d3.js像这样的标准代码:

group.selectAll('rect')
  .data(data)
.enter().append('svg:rect')
  .style('fill', colour)
  .on('mouseover', function(d, i) {
    chart.currentHoverItem = d
  })
  .on('mouseout', function(d, i) {
    chart.currentHoverItem = null
 })

在我的代码中,我在不同的方法中有一些相同的行。理想情况下,我想这样做:

var addEvents() {
   this.on('mouseover', function(d, i) { ... })
   this.on('mouseout', function(d, i) { ... })
}

group.selectAll('rect')
  .data(data)
.enter().append('svg:rect')
  .apply(addEvents)

干燥此代码的最佳解决方案是什么?

4

1 回答 1

2

您可能正在寻找selection.call,试试这个:

function addEvents(selection) {
    selection.on(...);
    selection.on(...);
}

group.selectAll('rect')
    .data(data)
.enter()
    .append('svg:rect')
    .call(addEvents);
于 2012-10-25T07:20:16.813 回答