Using functions in multiple DataTables

Using functions in multiple DataTables

tabledoctabledoc Posts: 2Questions: 1Answers: 0

This may be more a basic JavaScript question, but I have a page with multiple DataTables that all use similar columnDefs, footerCalbacks, etc.

Is there a way to define the columnDefs, footerCallbacks, etc. once and reuse them in multiple DataTables? I find myself copy and pasting large segments of code.

For instance, one of my footerCallbacks to sum the column values looks like this and I have it copied into every DataTable breaking DRY principle.

Thanks!

      footerCallback: function (row, data, start, end, display) {
        var api = this.api(),
          data;

        // Remove the formatting to get integer data for summation
        const intVal = function (i) {
          return typeof i === 'string'
            ? i.replace(/[\$a-zA-Z, ]/g, '') * 1
            : typeof i === 'number'
            ? i
            : 0;
        };

        const cols = new Int8Array(
          document.getElementById('table_locations').rows[0].cells.length - 1
        ).map((curr, index) => (curr = index + 1));

        for (let index = 0; index < cols.length; index++) {
          const col_data = cols[index];
          // Total over all pages
          const total = api
            .column(col_data)
            .data()
            .reduce(function (a, b) {
              return intVal(a) + intVal(b);
            }, 0);

          // Total over this page
          const pageTotal = api
            .column(col_data, {
              page: 'current',
            })
            .data()
            .reduce(function (a, b) {
              return intVal(a) + intVal(b);
            }, 0);

          // Update footer
          $(api.column(col_data).footer()).html(`${pageTotal}/${total}`);
        }

This question has accepted answers - jump to:

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599
    Answer ✓

    Yep, that's more standard JS. You can make those callback functions, something like this. Likewise, you can make objects for the columns and other declarations that you just reuse.

    Colin

  • kthorngrenkthorngren Posts: 21,374Questions: 26Answers: 4,957
    Answer ✓

    Also checkout the docs for creating default options.

    Kevin

  • tabledoctabledoc Posts: 2Questions: 1Answers: 0

    Thanks! This was exactly what I was looking for. Still learning JS, but loving DataTables!

Sign In or Register to comment.