Show progress bar while knockout is rendering the view

http://stackoverflow.com/questions/8227704/show-progress-bar-while-knockout-is-rendering-the-view

by rniemeyer

HTML

<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
<div data-bind="text: percentComplete"></div>
<hr/>
<ul data-bind="foreach: realData">
    <li data-bind="text: name"></li>
</ul>

JavaScript

(function() {
    //our plain JS data has 1000 rows
    var initialData = [];  
    for (var i = 0; i < 1000; i++) {
        initialData.push({ id: i, name: "name " + i });   
    }
    
    
    var viewModel = {
        realData: ko.observableArray(),
    };
    
    //track the percentage that we have pushed to the observableArray
    var total = initialData.length;
    viewModel.percentComplete = ko.dependentObservable(function() {
        return (this.realData().length / total * 100).toFixed(0);
    }, viewModel);    
    
    //push 10 at a time in a setTimeout, where the callback calls initiates this functiona again
    var numToPush = 10;
    function pushInitialData() {
        if (initialData.length) {
            var data = initialData.splice(0, numToPush);
            setTimeout(function() {
                ko.utils.arrayPushAll(viewModel.realData(), data);
                viewModel.realData.valueHasMutated();
                pushInitialData();
            }, 0);
        }  
    }
    
    //binding against an empty array to start with
    ko.applyBindings(viewModel);
    
    //start pushing
    pushInitialData();

})()