Knockout.JS - Bindings - Components
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>Component</h4>
<main class="summary">
<div class="fifty">
<p>First instance, without parameters</p>
<div data-bind='component: "message-editor"'></div>
</div>
<div class="fifty last">
<p>Second instance, passing parameters</p>
<div data-bind='component: {
name: "message-editor",
params: { initialText: "Hello, world!" }
}'></div>
</div>
</main>
CSS
body {
background: rgba(247, 243, 222, 0.9);
color: #777;
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,
select {
box-sizing: border-box;
border: 1px solid rgba(139, 116, 61, 0.6);
padding: 0.5em 1em;
width: 100%;
}
button:focus,
input:focus,
select:focus {
border: 1px solid rgba(139, 116, 61, 1);
box-shadow: 0;
outline: 0;
}
select {
height: 10em;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-weight: bold;
margin: 0;
}
h2 {
font-size: 2em;
margin: 0;
}
h4 {
font-size: 1.2em;
margin-bottom: 1em;
}
form,
main {
margin: 1.5em auto;
max-width: 90%;
}
main {
padding: 0.5em 1em;
position: relative;
}
main p {
margin-top: 0;
}
ol,
ul {
text-align: left;
}
p {
font-size: 0.9rem;
margin: 1em 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%;
}
.buttons {
box-sizing: border-box;
height: 2em;
}
.buttons button {
border-color: rgba(0, 0, 0, 0.15);
border-radius: 3px;
box-sizing: border-box;
color: #fff;
cursor: pointer;
display: inline-block;
font-size: 0.7em;
height: 2em;
margin: 1em 0 0;
max-width: 32%;
outline: none;
text-transform: uppercase;
}
.buttons button:disabled {
cursor: default;
opacity: 0.3;
}
.buttons button:last-of-type {
margin-right: 0;
}
#add {
background: #8d8;
}
#clear {
background: rgba(139, 116, 61, 0.9);
}
#remove {
background: #f88;
}
#status-container {
margin: 0.5em 0 0;
text-align: left;
}
#status-container span {
color: #6c6;
font-weight: bold;
}
#status-container span.error {
color: #c66;
}
.fifty {
float:...
JavaScript
ko.components.register('message-editor', {
viewModel: function(params) {
this.text = ko.observable(params && params.initialText || '');
},
template: '<p>Message: <input data-bind="value: text" /></p>' + '<p>(length: <span data-bind="text: text().length"></span>)</p>'
});
ko.applyBindings();