Knockout.JS - Modelo de vista (Editable)

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>Editable</h4>

<form class="data">
    <p>First name:
        <input data-bind="value: firstName" />
    </p>
    <p>Last name:
        <input data-bind="value: lastName" />
    </p>
    <button data-bind="click: capitalizeLastName">Go caps</button>
    <button data-bind="click: resetLastName">Reset caps</button>
</form>
<main class="data-summary">
    <h4>
    Summary
    </h4>
    <p>Your first name is <strong data-bind="text: firstName"></strong>.</p>
    <p>Your last name is <strong data-bind="text: lastName"></strong>.</p>
    <p>Your full name is <strong data-bind="text: fullName"></strong>.</p>
</main>

<p class="credit">Fuente: <a href="http://learn.knockoutjs.com/#/?tutorial=intro" target="_blank">Introducción a Knockout</a></p>

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;
    margin-bottom: 1em;
}

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

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

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

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

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

JavaScript

var firstName = "Bert",
    lastName = "Bertington";

function AppViewModel() {
    this.firstName = ko.observable(firstName);
    this.lastName = ko.observable(lastName);

    this.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();
    }, this);

    this.capitalizeLastName = function() {
        var currentVal = this.lastName(); // Read the current value
        this.lastName(currentVal.toUpperCase()); // Write back a modified value
    };

    this.resetLastName = function() {
        var currentVal = this.lastName(); // Read the current value
        this.lastName(currentVal.substr(0, 1) + currentVal.toLowerCase().substr(1, currentVal.length)); // Write back a modified value
    };
}
ko.applyBindings(new AppViewModel());