JSFiddle - React, Tailwind, and code Playground

by bullrout

HTML

<script src="https://github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.js"></script>
<script src="https://raw.github.com/SteveSanderson/knockout.mapping/master/build/output/knockout.mapping-latest.js"></script>
<script src="http://jquery-json.googlecode.com/files/jquery.json-2.3.min.js"></script>
<center>
    <table class="border">
        <tbody data-bind="foreach: matrix">
            <tr>
                <td data-bind="text: a"></td>
                <td data-bind="text: b"></td>
            </tr>
        </tbody>
    </table>
<button data-bind="visible:matrix().length == 0, click: loadMatrix" width="200" height="100">Load matrix</button>
<button data-bind="visible:matrix().length > 0, click: change" width="200" height="100">Change</button>

CSS

.border
{
 border: 2px solid green;   
}

JavaScript

// Sample JSON to return for initialization; 2 second delay
var data = {
    json: $.toJSON({matrix: [{a:1, b: 2},{a:2, b:3},{a:3, b:4}]}),
        delay: 0.1
}

// Sample JSON to return for initialization; 2 second delay
var data2 = {
    json: $.toJSON({matrix: [{a:2, b:4},{a:4, b:5}]}),
        delay: 0.1
}

var dataMapping = {
    'matrix': {
        key: function(data) {
            return ko.utils.unwrapObservable(data.a);
        },
        create: function(options) {
            console.log('Creating: ' + options.data.a);
            return new DataModel(options.data);
        },
        update: function(options) {
            console.log('Updating: ' + options.data.a);
            return options.target;
        }
     }
}

var DataModel = function(data) {
    this.a = ko.observable(data.a);
    this.b = ko.observable(data.b);
}            
    
function ViewModel() { 
  var self = this;
self.matrix = ko.observableArray([]);
  self.loadMatrix = function() {
      // Use JSFiddle echo to simulate an AJAX service
      $.ajax({ url:"/echo/json/", data:data, type:"POST",
               success:function(data)
               {
                 // Map the returned JSON to the View Model  
                   ko.mapping.fromJS(data, dataMapping, self);
                }
              })
     
  };
      
  self.change= function() {
      // Use JSFiddle echo to simulate an AJAX service
      $.ajax({ url:"/echo/json/", data:data2, type:"POST",
               success:function(data)
               {
                  // Map the returned JSON to the View Model  
                  ko.mapping.fromJS(data, self);
                }
              })
  };
};  

ko.applyBindings(new ViewModel());