http://stackoverflow.com/questions/10231347/knockout-afterrender-but-just-once

http://stackoverflow.com/questions/10231347/knockout-afterrender-but-just-once

by rniemeyer

HTML

<script src="http://github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.js"></script>
<table data-bind="template: { name: 'itemTmpl', foreach: items }, updateTableOnce: true">
</table>

<hr/>

<table data-bind="template: { name: 'itemTmpl', foreach: items }, updateTableEachTimeItChanges: items">
</table>

<button data-bind="click: addItem">Add Item</button>

<script id="itemTmpl" type="text/html">
    <tr>
        <td data-bind="text: id"></td>
        <td data-bind="text: name"></td>
    </tr>
</script>

JavaScript

var getRandomColor = function() {
   return 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';  
};

ko.bindingHandlers.updateTableOnce = {
    init: function(element) {
        $(element).css("color", getRandomColor());            
    }    
};

//this binding currently takes advantage of the fact that all bindings in a data-bind will be triggered together, so it can use the "foreach" dependencies.  Otherwise, you can pass "items" to it and unwrap it to grab a dependency
ko.bindingHandlers.updateTableEachTimeItChanges = {
    update: function(element, valueAccessor) {    
        ko.utils.unwrapObservable(valueAccessor());  //grab dependency
        $(element).css("color", getRandomColor());  
    }    
};


var viewModel = {
    items: ko.observableArray([
        { id: 1, name: "one" },
        { id: 1, name: "one" },
        { id: 1, name: "one" }
    ]),
    addItem: function() {
        this.items.push({ id: 0, name: "new" });   
    }
};

ko.applyBindings(viewModel);