Using a call-back function within datatables buttons extension

I'm using jQuery Datatables buttons extension.

       "buttons": [
            {
                extend: 'colvis', //column visibility
                className: 'data_export_buttons'
            },
            {
                extend: 'print',
                className: 'data_export_buttons',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'excel',
                className: 'data_export_buttons',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'csv',
                className: 'data_export_buttons',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'pdf',
                className: 'data_export_buttons',
                exportOptions: {
                    columns: ':visible'
                }
            }
        ]

Everything works, however, I would like to use the above code as a call-back function. So instead of repeating the same lines across all my tables (I have over 15), I would just call the function like this:

   var table = $('#table').DataTable({ 
        "paging": true,
        "info": false,
        "ordering": true,
        "columnDefs": [
            { "targets": [0], "orderable": false}
        ],
        export_data() // the call-back function for colvis and export button extensions
    });

I have tried this but it didn't work. My table lost data. Is there a way to achieve this?

1 answer

  • answered 2018-04-14 14:31 colin0117

    Yep, you can't do a callback there, but a just as tidy way would be to create a variable, something like

    myButtons = [
            {
                extend: 'colvis', //column visibility
                className: 'data_export_buttons'
            },
            // snip
        ];
    

    Then, when you create your tables:

       var table = $('#table').DataTable({ 
        "paging": true,
        "info": false,
        "ordering": true,
        "columnDefs": [
            { "targets": [0], "orderable": false}
        ],
        "buttons": myButtons
    });