JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://github.com/downloads/SteveSanderson/knockout/knockout-1.3.0beta.js"></script>
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 id="header" data-bind="afterRender: afterRenderFixup1"><th>Name</th><th>Capital</th><th>Code</th></tr>
</thead>
<tbody data-bind="foreach: {data: fetchedData, afterRender: afterRenderFixup}">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: capitalCity"></td>
<td data-bind="text: iso2Code"></td>
<td></td>
</tr>
</tbody>
</table>
<hr/>
Done <strong data-bind="text: queriesDone"></strong> Ajax request(s)
CSS
table { border-collapse:collapse }
th { text-align: left; background-color: #350; color: white; }
th, td { padding: 4px; }
.odd { background-color: #e5e5e5; }
JavaScript
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);
}
}
afterRenderFixup1 = function(element) {
//alert(0);
//$("#header").append("<th>Test</th>");
}
afterRenderFixup = function(element) {
// checkIndex is a HACK!!!!!!
// it has to be this way because FF and IE use different index numbers.
var checkIndex = $.browser.msie ? 0 : 1;
var i2 = ko.contextFor(element[checkIndex]);
if(!i2.$parent.currentRowNumber)
i2.$parent.currentRowNumber = 0;
var i3 = i2.$parent.currentRowNumber + 1;
i2.$parent.currentRowNumber = i3;
console.log(i2.$parent.currentRowNumber);
i3 = i3 % 2;
if (1 === i3) $(element[checkIndex]).addClass('odd');
}
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
});