observable arrays in KnockoutJS and table updates

observable arrays in KnockoutJS and table updates

getalexgetalex Posts: 39Questions: 11Answers: 1

Following this pattern:

https://datatables.net/dev/knockout/

Instead of the deprecated array subscription model used in the example, I am using the following:

myResults = ko.mapping.fromJS([]); // an observable array
myResults.subscribe(function (changes) {
        //console.log(changes);
        for (var i = 0; i < changes.length; i++) {
            var item = changes[i];
            switch (item.status) {
                case "deleted":
                    var rowIdx = dt.column(1).data().indexOf(item.value.Id);
                    dt.row(rowIdx).remove();
                    break;
                case "added":
                    dt.row.add(item.value);
                    break;
            }
        }
        dt.draw(); // moved draw function here after all changes are processed...
    }, null, "arrayChange");

I found moving draw out of the for loop improves performance significantly but i still have to call draw again after changes, the row isn't removed from the data table view for some reason - if i had 120 records, i'll see 119 in the paging control but the deleted item is still showing up on the table.

I also had the code below as in the example: but i notice it gets called multiple times and doesnt' quite invalidate the row, it still shows the older data unless I explicitly edit the dt.row(rowIdx).data() object ...

$.each(['VerifiedBy', 'VerifiedOn', 'OtherField'], function (i, prop) {
        that[prop].subscribe(function (val) {
            // Find the row in the DataTable and invalidate it, which will cause DataTables to re-read the data
            var rowIdx = dt.column(1).data().indexOf(that.Id);
            dt.row(rowIdx).invalidate();
        });

I'm trying to figure out how to call draw effectively and how to make changes render, and having quite a difficult time with it - i'll post a live example when I get a chance, for now any feedback on this would be great.

Replies

  • allanallan Posts: 63,455Questions: 1Answers: 10,465 Site admin

    Are you able to give me a link to your page showing the issue please? I'm not sure why the row().remove() isn't working there. I wonder if its related to the observables. You might be better just removing it from the data source rather than in DataTables.

    Allan

This discussion has been closed.