JSFiddle - React, Tailwind, and code Playground

by StevenSanderson

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)

<hr/>
<table>
    <thead><tr><th><b>Name</b></th><th><b>Capital</b></th><th><b>Code</b></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)

CSS

th { text-align: left; }

JavaScript

function myViewModel() {
    this.allowedPageSizes = [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(10);
    this.fetchedData = ko.observableArray([]);
    this.queriesDone = ko.observable(0);
    
    // Whenever "chosenRegion" or "numberToShow" changes, repopulate "fetchedData"
    ko.dependentObservable(function() {        
        $.ajax("http://api.worldbank.org/country?prefix=?", {
            dataType: "jsonp",
            data: { per_page: this.numberToShow, region: this.chosenRegion, format: "jsonp" }
        }).done(function(data) { 
            this.queriesDone(this.queriesDone() + 1);
            this.fetchedData(data[1]);
        }.bind(this))    
    }, this);
}

ko.applyBindings(new myViewModel());