JSFiddle - React, Tailwind, and code Playground
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script>
<script src="http://jquery-json.googlecode.com/files/jquery.json-2.2.min.js"></script>
<BODY>
CPULOAD: <SPAN data-bind="text: cpuload"></SPAN><br/>
DISKLOAD: <SPAN data-bind="text: diskload"></SPAN><br/>
MEMLOAD : <SPAN data-bind="text: memload"></SPAN><br/>
<input type="button" class="getData" value="Get Data"/><br/>
<span class='warning' data-bind="visible: isMelting()">HOLY CRAP IT IS MELTING</span>
</BODY>
CSS
.warning {
color:#ff0000;
background-color:#f0f0f0;
font-weight:bold;
}
JavaScript
var bogus = { //this is for jsfiddle only, to simulate AJAX calls
json: $.toJSON({
cpuload: '99', //change this to less than 90 to not get 'melting' warning
diskload: '55',
memload: '33'
}),
delay: 0
};
var MyServerInfo;
$(document).ready(function () {
MyServerInfo = new ViewModel({
"cpuload": 0,
"diskload": 0,
"memload": 0
});
ko.applyBindings(MyServerInfo); //POW. MyServerInfo is now married to HTML.
console.log("CPU: " + MyServerInfo.cpuload()); //demonstrates we can access data
$('.getData').on('click', function () { //bogus up data button on-click
$.ajax({
url: "/echo/json/",
data: bogus, //jsfiddle requires we post what we want back, you probably won't
type: "POST", //use a POST to get your data, so can ignore these two.
success: function (response) {
//this right here is what usually trips up new folk. This refreshes your
//existing mappings (MyServerInfo) with your new data (response).
ko.mapping.fromJS(response, {}, MyServerInfo);
console.log(response);
if (response.cpuload > 90){
MyServerInfo.isMelting(true); //now change my custom field
}
}
});
});
});
//self defining ViewModel. It'll make itself the shape of whatever you give it in JSON.
function ViewModel(data) {
data = data || {}; var self = this;
self = ko.mapping.fromJS(data);
self.isMelting = ko.observable(false); //you can add to ko.mapping, if you need more.
return self;
}
//this isn't used, it just demonstrates NOT using ko.mapping, and rolling your own.
function HandBuiltViewModel(data) {
data = data || {}; var self = this;
self.cpuload = ko.observable(data.cpuload);
self.memload = ko.observable(data.memload);
self.diskload = ko.observable(data.diskload);
self.isMelting =...