views:

36

answers:

2

I am using the DataTables jQuery plugin. The way I want my tables to work though mean I am passing a lot of parameters to the plugin to turn off things:

$('table.data').dataTable( {
    'aoColumns': [
        null,
        { 'bSortable': false },
        { 'bSortable': false },
        { 'asSorting': ['desc','asc'], 'sType': 'blanks' },
        { 'asSorting': ['desc','asc'] }
    ],
    'bPaginate': false,
    'bAutoWidth': false,
    'bInfo': false,
    'bProcessing': true,
    'asStripClasses': [],
    'sDom': 'rt'
} );

Across different pages, the aoColumns parameter will change based on the table, but the other parameters stay the same. What would be the best way to save me repeating code over and over (and make it easier if I change my mind about a parameter later)?

I tried storing a parameter with {'bPaginate': false ...} but that creates a sub-object. Maybe there is a way to "merge" objects inline or something?

+2  A: 

Place the reused ones in a variable:

var reused = {
   'bPaginate': false,'bAutoWidth': false,
    'bInfo': false,
    'bProcessing': true,
    'asStripClasses': [],
    'sDom': 'rt'
}

Then use $.extend to merge the unique data:

$('table.data').dataTable( 
    $.extend(
        {},  // Empty target that is extended and passed to dataTable 
        reused, // Extend with the stored reused data
        {'aoColumns': [ // Extend with an object containing the unique propertie(s)
               null,
               { 'bSortable': false },
               { 'bSortable': false },
               { 'asSorting': ['desc','asc'], 'sType': 'blanks' },
               { 'asSorting': ['desc','asc'] }
            ]
        }
    )
);

EDIT: One of my closers was } instead of ). Fixed.

Note that if you want to override one of your reused properties, you can just add another object to the $.extend() anywhere after the reused variable. This doesn't affect the items stored in reused.

$.extend(
        {},  
        reused,
        {'bInfo': true}, // override one of the properties in "reused"
        {aoColumns:// ...etc
patrick dw
+2  A: 

If you do this often, you could add your own jQuery plugin:

jQuery.fn.myDataTable = function(aoColumns) {
    return this.dataTable({
        'aoColumns': aoColumns,
        'bPaginate': false,
        'bAutoWidth': false,
        'bInfo': false,
        'bProcessing': true,
        'asStripClasses': [],
        'sDom': 'rt'
    });
};
Douglas