Knockout.JS - Modelo de vista (Colecciones)

Un ejemplo de un modelo de vista en Knockout, tomado del sitio oficial.

by Marventus

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<h2>Modelo de Vista</h2>
<h4>Colecciones</h4>

<form data-bind="submit: addItem">
    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="50" data-bind="options: items"> </select>
</form>

CSS

body {
    background: rgba(247, 243, 222, 0.9);
    color: #666;
    font: 16px Arial, Helvetica, sans-serif;
    max-width: 100%;
    margin: 0 auto;
    padding: 1em 3em;
    text-align: center;
}

a,
a:hover,
a:visited,
a:active,
a:focus,
h2 {
    color: rgb(139, 116, 61);
}

button,
input {
    border: 1px solid rgba(139, 116, 61, 0.9);
    padding: 0.3em 0.6em;
}

button {
    background: rgba(139, 116, 61, 0.9);
    border-radius: 3px;
    color: #fff;
    cursor: pointer;
    margin-top: 1em;
    padding: 0.5em 1em;
    outline: none;
    text-transform: uppercase;
}

h1,
h2,
h3,
h4,
h5,
h6 {
    margin: 0;
}

h2 {
    font-size: 2em;
    margin: 0;
}

h4 {
    font-size: 1.5em;
}

form,
main {
    margin: 1em auto;
    max-width: 50%;
}

main {
    background: #fff;
    border: 1px solid rgba(139, 116, 61, 0.9);
    padding: 0.5em 1em;
    position: relative;
}

p {
    font-size: 0.9rem;
    margin: 0.5em 0 0;
}

.credit {
    background: rgba(0, 0, 0, 0.1);
    font-size: 0.8em;
    margin-top: 3em;
    padding: 0.5em 1em;
    text-align: right;
    width: 100%;
}

@media only-screen and (maax-width: 30em) {}

JavaScript

var SimpleListModel = function(items) {
    this.items = ko.observableArray(items);
    this.itemToAdd = ko.observable("");
    this.addItem = function() {
        if (this.itemToAdd() != "") {
            this.items.push(this.itemToAdd()); // Adds the item. Writing to the "items" observableArray causes any associated UI to update.
            this.itemToAdd(""); // Clears the text box, because it's bound to the "itemToAdd" observable
        }
    }.bind(this);  // Ensure that "this" is always this view model
};
 
ko.applyBindings(new SimpleListModel(["John", "Paul", "George"]));