0

我正在使用我编写的一些 d3 代码开发一个小型图表库。我一直在为各种用例向我的图表添加配置/自定义选项,而我一直遇到的事情是冲突的事件处理程序。

转换有时会给我带来麻烦,但我的问题比这更笼统。在我的图表中执行一组事件处理程序的好方法是什么?

我使用的一种方法是建立一个处理程序的文字数组,然后遍历列表,执行每个处理程序:

function chart(selection) {
  selection.each(function(data) {

    // initial config and options, including the handlers array
    var margin = {top: 20, right: 20, bottom: 50, left: 40},
        ...
        fadeOnHover = true,
        barMouseoutHandlers = [],
        barMouseoverHandlers = [];


    // create the chart


    // an option
    if (fadeOnHover) {
      barMousemoveHandlers.push(function(d, i) {
        selection.selectAll('.bar').filter(function(d, j){return i!=j;})
          .transition().duration(100).style('opacity', '.5');
        selection.selectAll('.bar').filter(function(d, j){return i==j;})
          .transition().duration(100).style('opacity', '1');
      });

      barMouseoutHandlers.push(function() {
        selection.selectAll('.bar').transition().duration(100).style('opacity', '1');
      });
    }

    // other options, which may add handlers

    // then at the end of the function, execute all handlers
    g.selectAll('.bar')
      .on('mouseover', function(d, i) {
        barMouseoverHandlers.forEach(function(handler) { handler(d, i); });
      })
      .on('mouseout', function(d, i) {
        barMouseoutHandlers.forEach(function(handler) { handler(d, i); });
      });
  });
}

这就是我在我的图表中添加一些功能时提出的问题,但它显然不是非常模块化或组织良好。也许有空间将其中一些片段提取到单独的对象中。

还有哪些其他方法?我很想听听你对此的任何想法。

4

1 回答 1

2

我认为您只需要“命名空间”多个事件,这样它们就不会覆盖先前注册的事件。像这样的东西:

g.selectAll('.bar')
  .on('mouseover.one', function(d, i) {
    // do something
  })
  .on('mouseover.two', function(d, i) {
    // something else
  });

API

要为同一事件类型注册多个侦听器,该类型后面可以跟一个可选的命名空间,例如“click.foo”和“click.bar”。

于 2013-08-19T14:03:00.550 回答