Knockout.JS - Bindings - With
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>With</h4>
<form data-bind="submit: getTweets">
Twitter account:
<input data-bind="value: twitterName" />
<button type="submit">Get tweets</button>
</form>
<main data-bind="with: resultData" class="summary">
<p>Recent tweets fetched at <strong data-bind="text: retrievalDate"> </strong></p>
<ol data-bind="foreach: topTweets">
<li data-bind="text: text"></li>
</ol>
<button data-bind="click: $parent.clearResults">Clear tweets</button>
</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: 75%;
}
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
function AppViewModel() {
var self = this;
self.twitterName = ko.observable('@example');
self.resultData = ko.observable(); // No initial value
self.getTweets = function() {
var name = self.twitterName(),
simulatedResults = [{
text: name + ' What a nice day.'
}, {
text: name + ' Building some cool apps.'
}, {
text: name + ' Just saw a famous celebrity eating lard. Yum.'
}];
self.resultData({
retrievalDate: new Date(),
topTweets: simulatedResults
});
}
self.clearResults = function() {
self.resultData(undefined);
}
}
ko.applyBindings(new AppViewModel());