Skip to content
Advertisement

Datatables CRUD operations

I am developing a tasking application that tracks tasks with various metadata for the tasks. When the task is created, the options are saved to a related list. However, the metadata tags may change as the task progresses. I am using DataTables to display the options. The below code loads in the full list of options, then the selected entries, and combines into an array to track changes. As buttons are pressed for primary or secondary, the array is updated for the appropriate action to the item, i.e. if it’s new, flag for create. If it has a list ID number, flag for update, and lastly mark any that have a listID but are not selected for delete. My prototype is working but I do not think I did it in an efficient manner and I am concerned that it will not scale well if I add a 3rd button for tertiary selection. The nested if statement are already getting crazy.

Right now, it is intended that selecting a new primary will clear out any existing secondary selections.

let fullList = [
    {id: "12",title: "A",code:"110"},
    {id: "23",title: "B",code:"120"},
    {id: "13",title: "C",code:"130"},
    {id: "43",title: "D",code:"140"},
    {id: "52",title: "E",code:"150"},
]

let selectList = [
    {listID: "488",id:"23",code:"120",weight:"Primary"},
    {listID: "234",id:"43",code:"140",weight:"Secondary"}
]

let workingList = [];

for (i = 0; i < fullList.length; i++) {
    workingList.push({'rowId':i,'id':fullList[i].id,'title':fullList[i].title,'code':fullList[i].code,'listID':'','weight':'','operation':''});
};

for (var i=0;i<workingList.length;i++) {
    for (var j=0;j<selectList.length;j++) {
        if(workingList[i].code == selectList[j].code) {
            workingList[i].operation = 'Read';
            workingList[i].listID = selectList[j].listID;
            workingList[i].weight = selectList[j].weight;
        }
    }
}

$(document).ready(function() {
    var table = $('#myTable').DataTable({
        processing: true,
        data: workingList,
        rowId: 'rowId',
        columnDefs: [
        {
            orderable: false
        },
    ],
    columns: [
            { data: 'title' },
            { data: 'code' },
            { data: 'weight'},
            { data: 'operation' },
            { data: 'listID' },
            {defaultContent: '<button class="btn-primary bg-primary">Primary</button>'},
            {defaultContent: '<button class="btn-secondary bg-secondary">Secondary</button>'},
        ],
        "rowCallback": function (row, data) {
            if (data.weight == "Primary") {
                $('td',row).eq(2).addClass('selected').addClass('bg-primary');
            }
            if (data.weight == "Secondary") {
                $('td',row).eq(2).addClass('selected').addClass('bg-secondary');
            }
          }
    }); 

    $('#myTable tbody').on('click', 'button.btn-primary', function () {
        var tr = $(this).closest('tr');
        var row = table.row(tr);
        var id = row.data().rowId;
        if ($(this).eq(2).hasClass('selected')) {
            $(this).eq(2).removeClass('selected');
            workingList[id].weight = '';
            if (workingList[id].operation == 'Read' || workingList[id].operation == 'Update') {
                workingList[id].operation = "Delete";
            }
            else {workingList[id].operation = ""};
        } else {
            table.$('tr.selected').removeClass('selected');
            $(this).eq(2).addClass('selected');
            workingList[id].weight = 'Primary';
            for (i = 0; i < workingList.length; i++) {
                if (i != id) {
                    workingList[i].weight = "";
                    if (workingList[i].listID != "") {
                        workingList[i].operation = "Delete";
                    }
                    else if (workingList[i].operation == "Create") {
                        workingList[i].operation = "";
                    }
                }
            }
            if (workingList[id].listID == '') {
                workingList[id].operation = "Create";
            }
            else {workingList[id].operation = "Update"};
        }

        table.clear().draw();
        table.rows.add(workingList); // Add new data
        table.columns.adjust().draw(); // Redraw the DataTable
        console.log(workingList[id]);
    });

    $('#myTable tbody').on('click', 'button.btn-secondary', function () {
        var tr = $(this).closest('tr');
        var row = table.row(tr);
        var id = row.data().rowId;
        if ($(this).eq(2).hasClass('selected')) {
            $(this).eq(2).removeClass('selected');
            workingList[id].weight = '';
            if (workingList[id].operation == 'Read' || workingList[id].operation == 'Update') {
                workingList[id].operation = "Delete";
            }
            else {workingList[id].operation = ""};
        } else {
            table.$('tr.selected').removeClass('selected');
            $(this).eq(2).addClass('selected');
            workingList[id].weight = 'Secondary';
            for (i = 0; i < workingList.length; i++) {
                if (i != id){
                    if (workingList[i].weight != 'Primary') {
                    workingList[i].weight = "";
                    };
                    if (workingList[i].listID != "") {
                        if (workingList[i].weight != 'Primary') {
                        workingList[i].operation = "Delete";
                        }
                    }
                    else if (workingList[i].operation == "Create") {
                        if (workingList[i].weight != 'Primary') {
                            workingList[i].operation = "";
                        }
                    }
                }
            }
            if (workingList[id].listID == '') {
                workingList[id].operation = "Create";
            }
            else {workingList[id].operation = "Update"};
        }

        table.clear().draw();
        table.rows.add(workingList); // Add new data
        table.columns.adjust().draw(); // Redraw the DataTable
        console.log(workingList[id]);
    });
})

http://live.datatables.net/salohoro/1/ is a working copy as well. Any advice on efficiency and scalability would be appreciated.

Advertisement

Answer

some very minor tweaks,

I changed

 if (workingList[i].weight != 'Primary') {
                    workingList[i].weight = "";
                    };
                    if (workingList[i].listID != "") {
                        if (workingList[i].weight != 'Primary') {
                        workingList[i].operation = "Delete";
                        }
                    }
                    else if (workingList[i].operation == "Create") {
                        if (workingList[i].weight != 'Primary') {
                            workingList[i].operation = "";
                        }
                    }

to

if (workingList[i].weight !== 'Primary') {
                        workingList[i].weight = "";
                        if (workingList[i].listID !== "") {
                            workingList[i].operation = "Delete";
                        }
                        else if (workingList[i].operation === "Create") {

to reduce the number of times you need to check for !== ‘Primary’

I changed “=” to “===” and “!=” to “!==” as that’s better practice to ensure exact matches and changed vars to let and const to ensure better data type consistency

As for the for loops they actually perform better as is, see this comparison of loop types and their respective performance results: https://github.com/dg92/Performance-Analysis-JS

The rest of it looks find, if you find scaling it up you hit performance issues then maybe refactor out some of the logic into individual functions that you can call with Web Workers, they will really help improve performance, see https://medium.com/jspoint/achieving-parallelism-in-javascript-using-web-workers-8f921f2d26db

let fullList = [
    { id: "12", title: "A", code: "110" },
    { id: "23", title: "B", code: "120" },
    { id: "13", title: "C", code: "130" },
    { id: "43", title: "D", code: "140" },
    { id: "52", title: "E", code: "150" },
]

let selectList = [
    { listID: "488", id: "23", code: "120", weight: "Primary" },
    { listID: "234", id: "43", code: "140", weight: "Secondary" }
]

let workingList = [];

for (i = 0; i < fullList.length; i++) {
    workingList.push({ 'rowId': i, 'id': fullList[i].id, 'title': fullList[i].title, 'code': fullList[i].code, 'listID': '', 'weight': '', 'operation': '' });
};

for (let i = 0; i < workingList.length; i++) {
    for (let j = 0; j < selectList.length; j++) {
        if (workingList[i].code === selectList[j].code) {
            workingList[i].operation = 'Read';
            workingList[i].listID = selectList[j].listID;
            workingList[i].weight = selectList[j].weight;
        }
    }
}

$(document).ready(function () {
    const table = $('#myTable').DataTable({
        processing: true,
        data: workingList,
        rowId: 'rowId',
        columnDefs: [
            {
                orderable: false
            },
        ],
        columns: [
            { data: 'title' },
            { data: 'code' },
            { data: 'weight' },
            { data: 'operation' },
            { data: 'listID' },
            { defaultContent: '<button class="btn-primary bg-primary">Primary</button>' },
            { defaultContent: '<button class="btn-secondary bg-secondary">Secondary</button>' },
        ],
        "rowCallback": function (row, data) {
            if (data.weight === "Primary") {
                $('td', row).eq(2).addClass('selected').addClass('bg-primary');
            }
            if (data.weight === "Secondary") {
                $('td', row).eq(2).addClass('selected').addClass('bg-secondary');
            }
        }
    });

    $('#myTable tbody').on('click', 'button.btn-primary', function () {
        let tr = $(this).closest('tr');
        let row = table.row(tr);
        let id = row.data().rowId;
        if ($(this).eq(2).hasClass('selected')) {
            $(this).eq(2).removeClass('selected');
            workingList[id].weight = '';
            if (workingList[id].operation === 'Read' || workingList[id].operation === 'Update') {
                workingList[id].operation = "Delete";
            }
            else { workingList[id].operation = "" };
        } else {
            table.$('tr.selected').removeClass('selected');
            $(this).eq(2).addClass('selected').addClass('bg-primary');
            workingList[id].weight = 'Primary';
            for (let i = 0; i < workingList.length; i++) {
                if (i !== id) {
                    workingList[i].weight = "";
                    if (workingList[i].listID !== "") {
                        workingList[i].operation = "Delete";
                    }
                    else if (workingList[i].operation === "Create") {
                        workingList[i].operation = "";
                    }
                }
            }
            if (workingList[id].listID === '') {
                workingList[id].operation = "Create";
            }
            else { workingList[id].operation = "Update" };
        }

        table.clear().draw();
        table.rows.add(workingList); // Add new data
        table.columns.adjust().draw(); // Redraw the DataTable
        console.log(workingList[id]);
    });

    $('#myTable tbody').on('click', 'button.btn-secondary', function () {
        let tr = $(this).closest('tr');
        let row = table.row(tr);
        let id = row.data().rowId;
        if ($(this).eq(2).hasClass('selected')) {
            $(this).eq(2).removeClass('selected');
            workingList[id].weight = '';
            if (workingList[id].operation === 'Read' || workingList[id].operation === 'Update') {
                workingList[id].operation = "Delete";
            }
            else { workingList[id].operation = "" };
        } else {
            table.$('tr.selected').removeClass('selected');
            $(this).eq(2).addClass('selected');
            workingList[id].weight = 'Secondary';
            for (let i = 0; i < workingList.length; i++) {
                if (i !== id) {
                    if (workingList[i].weight !== 'Primary') {
                        workingList[i].weight = "";
                        if (workingList[i].listID !== "") {
                            workingList[i].operation = "Delete";
                        }
                        else if (workingList[i].operation === "Create") {
                            workingList[i].operation = "";
                        }
                    }
                }
            }
            if (workingList[id].listID == '') {
                workingList[id].operation = "Create";
            }
            else { workingList[id].operation = "Update" };
        }

        table.clear().draw();
        table.rows.add(workingList); // Add new data
        table.columns.adjust().draw(); // Redraw the DataTable
        console.log(workingList[id]);
    });
})

I hope this helps

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement