"Safe" Base Fiddle

1.12 Knockout jQuery templates from KO downloads

by photo_tom

HTML

<script src="https://github.com/downloads/SteveSanderson/knockout/jquery.tmpl.js"></script>
<script src="http://github.com/downloads/SteveSanderson/knockout/knockout-1.1.2.js"></script>
<script src="http://datatables.net/release-datatables/media/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="http://datatables.net/release-datatables/media/css/demo_table.css">
<button data-bind="click: adicionarDados">Adicionar Dados</button>
<table data-bind="dataTable: {options: VM.tableOptions,object: VM.dataTable,rowClick: VM.tableRowClick,data: VM.tableData}">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Nome</th>
                    <th>Sobrenome</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>

JavaScript

ko.bindingHandlers.dataTable = {
  init: function(element, valueAccessor) {
    var options = valueAccessor();
    var defaults = {
        "aaData": options["data"](),
        "bRetrieve": true,
        "fnRowCallback": function(nRow, aData, iDisplayIndex) {
            $(nRow).mouseover(function(){
              $(nRow).attr("style","background-color:yellow !important;");
            });  
            $(nRow).mouseout(function() {
              $(nRow).removeAttr("style");
            });
            if(typeof options["rowClick"] === "function") {
              $(nRow).click(function() {
                options["rowClick"](aData);
              });  
            }  
            return nRow;
        },    
    }      
    var tableOptions = $.extend(defaults,options["options"]);
    options["object"]($(element).dataTable(tableOptions));
  },
  update: function(element,valueAccessor) {
    var options = valueAccessor();
    options["object"]().fnClearTable();
    options["object"]().fnAddData(options["data"](),true);
  }
};

var VM = {
    tableData: ko.observableArray([[1,"John","Doe"],[2,"Lorem","Ipsum"]]),
    dataTable: ko.observable(null),
    tableRowClick: function(data) { alert("O id é "+data[0]); },
    tableOptions: { aaSorting: [["1","desc"]] },
    idx: 2,
    adicionarDados: function() {
        VM.idx++;
        VM.tableData.push([VM.idx,"Teste"+VM.idx,"1234"+VM.idx]);
    }
};

$(function() {    
   ko.applyBindings(VM);
});