JSFiddle - React, Tailwind, and code Playground
by Jaganathan
HTML
<div class="header">Observable:</div>
<div>---------------------<div>
<input type="text" data-bind="value: name" />
You have typed : <label data-bind="text: name"></label>
<div class="header">Computed:</div>
---------------------
<div class="header">Message: </div><span data-bind="text: message"> </span>
<div class="header">Writable Computed:</div>
---------------------
<p>First Num: <span data-bind="text: firstNum"></span></p>
<p>Second Num: <span data-bind="text: secondNum"></span></p>
<h4>Result: <input data-bind="value: result"/>!</h4>
<div class="header">ObservableArray: </div>
--------------------
<div class="container" data-bind="foreach: texts">
<span data-bind="text: simpleText"></span>
<span class="remove" data-bind="click: $parent.removeItem.bind($parent, $data)">remove</span><br/>
</div>
<button data-bind="click: addText"> Add Item </button>
CSS
.container
{
background: green;
width: 300px;
margin-top: 20px;
max-height: 200px;
overflow: auto;
}
.header {
margin-top: 10px;
}
.remove { margin-left: 10px; cursor: pointer; }
JavaScript
var viewModal = {name: ko.observable("").extend({log: 'Name '})};
viewModal.message = ko.computed(function()
{
return "Hello " + this.name();
}, viewModal);
viewModal.texts = ko.observableArray([{simpleText: "Item"}]);
viewModal.addText = function() { this.texts.push({simpleText: "Item"}); };
viewModal.removeItem = function(item) { this.texts.remove(item); };
viewModal.firstNum = ko.observable(100);
viewModal.secondNum = ko.observable(10);
viewModal.result = ko.computed({
read: function () {
return this.firstNum() / this.secondNum();
},
write: function (value) {
this.firstNum(value * this.secondNum());
},
owner: viewModal
});
//Source: KnockoutJS.com
ko.extenders.log = function(target, option) {
target.subscribe(function(newValue) {
console.log(option + ": " + newValue);
});
return target;
};
ko.applyBindings(viewModal);