Search code examples
javascriptd3.jsdc.jscrossfilter

dc.js Row chart default view sorted and not reorder while onclick


I have a situation where displaying two-row chart side by side. I need to achieve sorting both the graph with group highest value, this I can achieve through chart.order(). Scenario:-

1. The initial load of the chart with sorted values.
2. on Click of the chart, Don't need the sorting or reordering of the bar. 
Filter can apply the chart without reordering the bar position

Is there any solution available?

jsFiddle


Solution

  • Interesting question. I think the simplest way to do this is just to take a snapshot of the values after the first render, and then use that for subsequent redraws.

    We'll put this into a reusable function that creates an event handler for the postRender event:

    function save_first_order() {
        var original_value = {}; // 1
        return function(chart) {
            chart.group().all().forEach(function(kv) { // 2
                original_value[kv.key] = kv.value;
            });
            chart.ordering(function(kv) { // 3
                return -original_value[kv.key];
            });
        };
    }
    

    The postRender event is fired only after the first time the chart is rendered (drawn). This function

    1. keeps its own map of values in the closure: the map will only be affected by the chart it's applied to
    2. when the render happens, it preserves all the values from the current `group.all() in that map, and
    3. changes the ordering function to use the values in the map instead of the current values

    This assumes, of course, that no new values appear later on, but I think that's an implicit assumption in your question.

    I put it inside a function so it can be reused, and applied it to both charts like so:

    rowChart
      // ...
        .on('postRender', save_first_order());
    

    (Note that the reusable function is called in order to create the closure, and it returns a function which is the actual event handler.)

    row chart not reordered

    Fork of your fiddle: http://jsfiddle.net/gordonwoodhull/04fcvgvu/5/