Knockout.JS - Modelo de vista (básico - objeto)

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>Básico - Objeto</h4>

<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>
    <hr>
    <p>Your full name is <strong data-bind="text: fullName"></strong>.</p>
</main>

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;
    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: 60%;
    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 (max-width: 30em) {
    main {
        max-width: 100%;
    }
    body {
        padding: 1em;
    }
}

JavaScript

var firstName = "Bert",
    lastName = "Bertington",
    viewModel = {
        firstName: ko.observable(firstName),
        lastName: ko.observable(lastName),
};
viewModel.fullName = ko.computed(function() {
	return this.firstName() + " " + this.lastName();
}, viewModel);

var appliedVm = viewModel,
	newVm = viewModel;
    
ko.applyBindings(appliedVm);

appliedVm.lastName("Jackson");

console.log(newVm.fullName());