Knockoutjs.com - Hello World Example
http://knockoutjs.com/examples/helloWorld.html
HTML
<script src="https://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
<div id="content" data-bind="with: object_to_work_with">
<select id="my_list" data-bind="options: $root.my_list,
optionsValue: 'value',
optionsText: 'title',
value: selected_model().value,
event: { change: $root.print_data }"></select>
<div id="data"></div>
</div>
CSS
#content {
padding: 30px;
margin: 30px;
background-color: #e9e9e9;
border: 1px solid #999999;
border-radius: 6px;
}
#data {
border-radius: 6px;
background-color: #ffffff;
padding: 20px;
margin-top: 20px;
}
JavaScript
class MyModel {
constructor(value, title) {
this.value = ko.observable(value);
this.title = ko.observable(title);
}
}
class MyWrapper {
constructor(selected_model) {
this.selected_model = ko.observable(selected_model);
}
}
class MyVM {
constructor() {
let items = [
new MyModel(1, 'One'),
new MyModel(2, 'Two'),
new MyModel(3, 'Three')
];
this.object_to_work_with = ko.observable(new MyWrapper(items[1]));
this.my_list = ko.observableArray(items);
}
print_data(wrapper, event) {
const selected_model = wrapper.selected_model();
const div = document.createElement('div');
const text = document.createTextNode(
`${selected_model.title()}: ${selected_model.value()}`
);
div.appendChild(text);
document.getElementById('data').appendChild(div);
}
}
ko.applyBindings(new MyVM());