JSFiddle - React, Tailwind, and code Playground

by gurkavcu

HTML

<script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-1.2.1.js"></script>
<script src="http://datatables.net/release-datatables/media/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/ui-lightness/jquery-ui.css">
<button data-bind="click: add">Add</button>
<button data-bind="click: remove">Remove</button>
<table data-bind="dataTable: tableData">
    <thead>
        <tr>
            <th>Col 1</th>
            <th>Col 2</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

CSS

table {
    border: 1px solid #000;
}
thead tr {
    background-color: #bbb;
}
tbody tr {
    background-color: #eee;
}
tbody tr:nth-child(even) {
    background-color: #ddd;
}

JavaScript

/* The dataTable binding */
(function($){
    ko.bindingHandlers.dataTable = {
        init: function(element, valueAccessor){
            var binding = ko.utils.unwrapObservable(valueAccessor());
            
            // If the binding is an object with an options field,
            // initialise the dataTable with those options. 
            if(binding.options){
                $(element).dataTable(binding.options);
            }
        },
        update: function(element, valueAccessor){
            var binding = ko.utils.unwrapObservable(valueAccessor());
            
            // If the binding isn't an object, turn it into one. 
            if(!binding.data){
                binding = { data: valueAccessor() }
            }
            
            // Clear table
            $(element).dataTable().fnClearTable();
            
            // Rebuild table from data source specified in binding
            $(element).dataTable().fnAddData(binding.data());
        }
    };
})(jQuery);

/* The ViewModel */
var dataTableExampleViewModel = {
    tableData: ko.observableArray([["Existing","Data"],["In An","observableArray"]]),
    add: function() {
        this.tableData.push([(new Date()).getTime(), "Added"]);
    },
    remove: function() {
        this.tableData.pop();
    }
};

/* Initialise the ViewModel */
$(function(){
    ko.applyBindings(dataTableExampleViewModel);
});