代码之家  ›  专栏  ›  技术社区  ›  DisgruntledGoat

如何缩短这些重复的jquery插件参数?

  •  2
  • DisgruntledGoat  · 技术社区  · 14 年前

    我正在使用数据表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 回复  |  直到 14 年前
        1
  •  2
  •   Douglas    14 年前

    如果你经常这样做,你可以添加你自己的 jQuery plugin :

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

    将重复使用的文件放在变量中:

    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() 之后的任何地方 再利用 变量。这不会影响存储在 再利用 .

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