DC.js - deselect feature or filter all but the ones that are clicked

孤者浪人 提交于 2019-12-02 03:33:57

It sounds like you want the same behavior except for the very first click, where you want to keep everything else and remove the clicked item if ctrl is pressed.

If there is anything selected, then a click should toggle as usual, whether or not ctrl is pressed.

As Ethan suggests, you could probably implement this as a filterHandler. That should work too, but since it's mostly the same behavior, I'd suggest using an override of onClick.

Unfortunately the technique for overriding this method is not pretty, but it works!

  var oldClick = rowChart.onClick;
  rowChart.onClick = function(d) {
      var chart = this;
      if(!d3.event.altKey)
          return oldClick.call(chart, d); // normal behavior if no mod key
      var current = chart.filters();
      if(current.length)
          return oldClick.call(chart, d); // normal behavior if there is already a selection
      current = chart.group().all()
          .map(kv => kv.key)
          .filter(k => k != d.key);
      chart.replaceFilter([current]).redrawGroup();
  };

I used the alt key instead of ctrl because ctrl-click on Macs is a synonym for right-click.

I'm using this on the rowcharts where I need this feature.
It's a little bit shorter than the other answer, maybe it can be useful to someone (I don't know which is better).

    // select only one category at a time
    mychart.onClick = function(_chart){ return function (d) {
        var filter = _chart.keyAccessor()(d);
        dc.events.trigger(function () {
            _chart.filter(null);
            _chart.filter(filter);
            _chart.redrawGroup();
        });
    }; }(mychart)

Where mychart is the name of your dc.rowchart

    var mychart = dc.rowChart('#mychart');

[EDIT]

This one works too, is shorter, and works with barcharts

    mychart.addFilterHandler(function (filters, filter) {
        filters.length = 0; // empty the array
        filters.push(filter);
        return filters;
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!