Datatables and Knockout Example

by Shrikrishna Gupta

HTML

<link rel="stylesheet" href="//cdn.datatables.net/1.10.4/css/jquery.dataTables.min.css">
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script>
<table cellpadding="0" cellspacing="0" border="0" class="display cell-border" id="example">
    <thead> 
        <tr> 
            <th>ID</th> 
            <th>Name</th> 
            <th>Age</th> 
        </tr> 
    </thead> 
    <tbody> 
    </tbody> 
</table> 
<div>
    <button id="update">Update</button>
</div> 
<div class="spacer"></div>
<div id = "model_data" ></div>

JavaScript

ko.observableArray.fn.subscribeArrayChanged = function(addCallback, deleteCallback) {
    var previousValue = undefined;
    this.subscribe(function(_previousValue) {
        previousValue = _previousValue.slice(0);
    }, undefined, 'beforeChange');
    this.subscribe(function(latestValue) {
        var editScript = ko.utils.compareArrays(previousValue, latestValue);
        for (var i = 0, j = editScript.length; i < j; i++) {
            switch (editScript[i].status) {
                case "retained":
                    break;
                case "deleted":
                    if (deleteCallback)
                        deleteCallback(editScript[i].value);
                    break;
                case "added":
                    if (addCallback)
                        addCallback(editScript[i].value);
                    break;
            }
        }
        previousValue = undefined;
    });
}


 var data = [
    { id: 0, first: "Allan", last: "Jardine", age: 86 },
    { id: 1, first: "Bob", last: "Smith", age: 54 },
    { id: 2, first: "Jimmy", last: "Jones", age: 32 }
]

var Person = function(data, dt) {
    var self = this;
    
    self.id    = data.id;
    self.first = ko.observable(data.first);
    self.last  = ko.observable(data.last);
    self.age   = ko.observable(data.age);

    // Subscribe a listener to the observable properties for the table
    // and invalidate the DataTables row when they change so it will redraw
    $.each( [ 'first', 'last', 'age' ], function (i, prop) {
        self[ 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( 0 ).data().indexOf( self.id );
            dt.row( rowIdx ).invalidate();
        } );
    } ); 
}

$(document).ready(function() {

    var people = ko.mapping.fromJS( [] );
    
    var dt = $('#example').DataTable( {
            "bPaginate": false,
          ...