stevenrskelton / sortable-table

Polymer Web Component that generates a sortable <table> from inlined or AJAX JSON, JSON5, and arrays.
https://stevenrskelton.github.io/sortable-table/
MIT License
196 stars 37 forks source link

Misinterpretation of array data and single row selection #44

Open nerk opened 9 years ago

nerk commented 9 years ago

Defining table data as an array of arrays leads to wrong construction of the selected data if table is in single-selection mode.

<sortable-table id="table"></sortable-table>

<script>
window.addEventListener('polymer-ready', function() {
   var table = document.getElementById('table');
   table.rowSelection = true;
   table.multiSelect = false;
   table.checkbox = true;
   table.data = [
        [ "apple", 4, 10, 2 ],
        [ "banana", 0, 4, 0 ],
        [ "grape", 2, 3, 5 ],
        [ "pear", 4, 2, 8 ],
        [ "strawberry", 0, 14, 0 ],
      ];

   table.addEventListener('click', function() {
        console.log(table.selected);
      });
});
</script>

After selecting 'banana' row with the mouse, console output is this:

["banana", 0, 4, 0]

However, after selecting 'apple', the output is this:

["banana", 0, 4, 0, Array[4]]

Array[4] is the 'apple' row which is appended as an element to the previously selected 'banana' row. Additionally selected rows will be appended in the same way.

The reason for this is the expression Array.isArray(this.selected) in various locations throughout the code, assuming that multiple-selection mode is active if this.selected contains an array.

Please also note that the 'check all' checkbox appears in the table header after the first selection, indicating the implicit mode switch from single- to multiple-selection mode.

So far, I commented out the code in selectedChanged and added a mode check in toggleRowFromSelected as follows:

toggleRowFromSelected: function (row) {
        if (this.multiSelect && Array.isArray(this.selected)) {
            var index = this.selected.indexOf(row);
...

This seems to fix the wrong construction of this.selected. However, in single-selection mode, checkboxes are now longer properly toggled.