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

前端 未结 2 1135
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-25 17:31

I\'m not sure if this is possible and no luck on researching this. I\'m working on a dashboard using DC.js charts and crossfilter.js. I\'m going to use a Row chart as an example

相关标签:
2条回答
  • 2021-01-25 17:58

    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;
        });
    
    0 讨论(0)
  • 2021-01-25 18:20

    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.

    0 讨论(0)
提交回复
热议问题