Simple Jquery Progress Bar

by James

HTML

<script src="http://github.com/downloads/SteveSanderson/knockout/knockout-2.2.0.js"></script>
<div id="progressBar" data-bind="progress: percentComplete"></div>
<hr/>
<ul data-bind="foreach: realData">
    <li data-bind="text: name"></li>
</ul>

CSS

div#progressBar:after {
    content: '';
  width: 50px;
  height: 50px;
  background-color: #000;
  z-index: 999;
}

div#progressBar:before {
    content: '';
  width: 50px;
  height: 50px;
  background-color: #000;
  z-index: 999;
}

JavaScript

ko.bindingHandlers.progress = {
    init: function(element, valueAccessor) {
        $(element).progressbar({
            value: 0
        });
    },
    update: function(element, valueAccessor) {
        var val = ko.utils.unwrapObservable(valueAccessor());
       $(element).progressbar("value", parseFloat(val));
    }
};

(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.computed(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();
            }, 50);
        }
    }

    //binding against an empty array to start with
    ko.applyBindings(viewModel);

    //start pushing
    pushInitialData();

})()