2010-08-28 37 views
2

我正在使用DataTables jQuery插件。我希望我的表,但工作方式意味着我路過很多的參數插件關閉的事情:如何縮短這些重複的jQuery插件參數?

$('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' 
}); 

在不同的頁面中,aoColumns參數的設置將根據該表,但其他參數保持原樣。什麼是最好的方式來節省我一遍又一遍的重複代碼(並且如果我稍後改變我對主要參數的看法,會更容易)?

我試圖用{'bPaginate': false ...}存儲一個參數,但是它創建了一個子對象。也許有一種方法來「合併」內聯對象或其他東西?

回答

2

如果你這樣做的時候,你可以添加自己的jQuery plugin

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

在一個變量重用的:

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

然後使用$.extend合併獨特的數據:

$('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'] } 
      ] 
     } 
    ) 
); 

編輯:我的一個閉門器是}而不是)。固定。

注意,如果你要覆蓋reused屬性之一,你可以添加其他對象到$.extend()reused變量之後的任何地方。這不會影響存儲在reused中的項目。

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