Created
February 7, 2017 04:09
-
-
Save matthiasak/4a6bf89be55fb8748df99f8fc8d068e1 to your computer and use it in GitHub Desktop.
ko.js example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// copy and paste into https://matthiasak.github.io/arbiter-frame/ | |
document.head.innerHTML += `<style> body { background: #efefef; } </style>` | |
document.body.innerHTML = ` | |
<p>First name: <input data-bind="value: first" /></p> | |
<p>Last name: <input data-bind='value: last, valueUpdate: "afterkeydown"' /></p> | |
<h2>Hello, <span data-bind="text: full"> </span>!</h2> | |
<hr/> | |
<div>You've clicked <span data-bind='text: clicks'> </span> times</div> | |
<button data-bind='click: click, disable: overClicked'>Click me</button> | |
<div data-bind='visible: overClicked'> | |
That's too many clicks! Please stop before you wear out your fingers. | |
<button data-bind='click: resetClicks'>Reset clicks</button> | |
</div> | |
<hr/> | |
<form data-bind="submit: addItems"> | |
New item: | |
<input data-bind='value: itemToAdd, valueUpdate: "afterkeydown"' /> | |
<button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button> | |
<p>Your items:</p> | |
<select multiple="multiple" width="500" data-bind="options: items"></select> | |
<select multiple="multiple" width="500" data-bind="options: items2"></select> | |
</form> | |
` | |
const app = $ => { | |
const ko = knockout | |
const ctor = (f,l) => { | |
const r = { | |
// 1 | |
first: ko.observable(f) | |
, last: ko.observable(l) | |
, full: ko.pureComputed($ => [r.first(), r.last()].join(' ')) | |
// 2 | |
, clicks: ko.observable(0) | |
, click: $ => r.clicks(r.clicks() + 1) | |
, overClicked: ko.pureComputed($ => r.clicks() >= 3) | |
, resetClicks: $ => r.clicks(0) | |
// 3 | |
, addItems: $ => | |
r.addItem() | |
&& r.addItem2() | |
&& r.itemToAdd('') | |
, addItem: $ => | |
r.itemToAdd() | |
&& r.items(r.items().concat(r.itemToAdd())) | |
, addItem2: $ => | |
r.itemToAdd() | |
&& r.items2(r.items2().concat(r.itemToAdd())) | |
, itemToAdd: ko.observable('') | |
, items: ko.observableArray(["burger", "fries", "shake"]) | |
, items2: ko.observable(["sushi", "ramen", "pho"]) | |
} | |
return r | |
} | |
const vm = ctor("planet", "earth") | |
ko.applyBindings(vm); | |
} | |
require('knockout').then(app).catch(e => log(e+'')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment