function myViewModel() { this.allowedPageSizes = [5, 10, 20, 50, 500]; this.allowedRegions = [ { name:"World", code:"WLD" }, { name:"Europe / Asia", code:"ECS" }, { name:"North America", code:"NAC" } ]; this.chosenRegion = ko.observable("WLD"); this.numberToShow = ko.observable(5); this.fetchedData = ko.observableArray([]); this.queriesDone = ko.observable(0); this.reset = function() { // We're changing two underlying observables, but because of throttling, // it will only trigger one Ajax call (the update is effectively atomic) this.chosenRegion("WLD"); this.numberToShow(5); } } var vm = new myViewModel(); ko.applyBindings(vm); // Whenever "chosenRegion" or "numberToShow" changes, repopulate "fetchedData" ko.dependentObservable(function() { $.ajax("http://api.worldbank.org/country?prefix=?", { dataType: "jsonp", data: { per_page: vm.numberToShow, region: vm.chosenRegion, format: "jsonp" }, success: function(data) { vm.queriesDone(vm.queriesDone() + 1); // Increment "queriesDone" vm.fetchedData(data[1]); } }); }).extend({ throttle: 1 });
Region: <select data-bind="options: allowedRegions, optionsText: 'name', optionsValue: 'code', value: chosenRegion"></select> Show: <select data-bind="options: allowedPageSizes, value: numberToShow"></select> record(s) <button data-bind="click: reset">Reset</button> <hr/> <table> <thead> <tr><th>Name</th><th>Capital</th><th>Code</th></tr> </thead> <tbody data-bind="foreach: fetchedData"> <tr> <td data-bind="text: name"></td> <td data-bind="text: capitalCity"></td> <td data-bind="text: iso2Code"></td> </tr> </tbody> </table> <hr/> Done <strong data-bind="text: queriesDone"></strong> Ajax request(s)