简体   繁体   中英

jQuery DataTables - Refactoring Code to remove 'aoColumn' duplication

I'm using jQuery DataTables to render a timeline and each column represents a day. I have a method that is called when each column (day) is rendered and it's passed in a date from an array.

Is there a better way to write the code below so that i'm not repeating myself 7 times whilst still being able to pass in the array item? I cannot see anything that stands out in the docs.

dataTable = $('#example').dataTable({
"bRetrieve":true,
"bProcessing":true,
"aaData": data,
// DataTables requires a render function for each column (day)
"aoColumns":[
    {
        "mData":null,
        "fnRender":function (obj) {
            return day(obj, week[0]);
        }
    },
    {
        "mData":null,
        "fnRender":function (obj) {
            return day(obj, week[1]);
        }
    },
    {
        "mData":null,
        "fnRender":function (obj) {
            return day(obj, week[2]);
        }
    },
    {
        "mData":null,
        "fnRender":function (obj) {
            return day(obj, week[3]);
        }
    },
    {
        "mData":null,
        "fnRender":function (obj) {
            return day(obj, week[4]);
        }
    },
    {
        "mData":null,
        "fnRender":function (obj) {
            return day(obj, week[5]);
        }
    },
    {
        "mData":null,
        "fnRender":function (obj) {
            return day(obj, week[6]);
        }
    }
]

});

Here is a simple solution, using $.map() :

dataTable = $("#example").dataTable({
    bRetrieve: true,
    bProcessing: true,
    aaData: data,
    aoColumns: $.map(Array(7), function(value, index) {
        return {
            mData: null,
            fnRender: function(obj) {
                return day(obj, week[index]);
            }
        };
    })
});

In the code above, Array(7) creates a sparse array of seven elements (indexed 0 to 6 ), all set to undefined . Then, $.map() projects object literals from the indices in that array. The result is an array of object literals with the second argument to day() varying with the current index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM