JSFiddle - React, Tailwind, and code Playground
by Mohammed Ismail Ansari
HTML
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js"></script>
<div id="input-div">
<span><b>First name: </b></span>
<input type="text" data-bind="value: firstName"></input>
<br />
<span><b>Last name: </b></span>
<input type="text" data-bind="value: lastName"></input>
<br />
<span><b>Age: </b></span>
<input type="text" data-bind="value: age"></input>
</div>
<br /><hr /><br />
<div id="display-div">
<span class="high"><b>Full name: </b></span>
<input type="text" data-bind="value: fullName"></input>
<br />
<span><b>Age: </b></span>
<input type="text" data-bind="value: age"></input>
</div>
CSS
body
{
font-family: Arial;
}
.high
{
color: Green;
}
JavaScript
// Writeable computed observables
// Our viewmodel with observables
function viewmodel() {
self = this;
// Regular observables
this.firstName = ko.observable("David");
this.lastName = ko.observable("Anderson");
this.age = ko.observable(50);
// Writeable computed observable: 'fullName'
this.fullName = ko.computed({
read: function() {
return self.firstName() + " " + self.lastName();
},
write: function(value) {
self.firstName(value.split(" ")[0]);
self.lastName(value.split(" ")[1]);
}
});
}
// Runs at document load
$(document).ready(function(){
// Create an instance of the viewmodel
var myViewmodel = new viewmodel();
// Bind the instance to the view
ko.applyBindings(myViewmodel);
});