Knockout Fire from OBJECT
by farina
HTML
<script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.js"></script>
<h3>Items</h3>
<button type="button" data-bind="click: addItem">Add</button>
<button type="button" data-bind="click: removeItem">Remove</button>
<button type="button" data-bind="click: clearItems">Clear</button>
<ul data-bind="template: { name: 'item-template', data: items, afterRender: caller }">
</ul>
<script type="text/html" id="item-template">
<!--ko foreach: $data-->
<li data-bind="text: name"></li>
<!-- /ko -->
</script>
You have <b data-bind="text: items().length"> </b> items(s)
<span data-bind="visible: items().length == 0"> - it's beer time!</span>
<ol class="grey"></ol>
<button id="clear_log">Clear Log</button>
CSS
html, body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, code, del, dfn, em, img, q, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td {
border: 0 none;
font-family: inherit;
font-size: 100%;
font-style: inherit;
font-weight: inherit;
margin: 0;
padding: 0;
vertical-align: baseline;
}
body {
background: none repeat scroll 0 0 #FFFFFF;
line-height: 1.5;
margin: 1.5em 0;
}
body, h1, h2, h3, h4, h5, h6, p, ul, ol, dl, input, textarea {
font-family: Helvetica,Arial,sans-serif;
}
ul, ol {
margin: 0 1.5em 1.5em;
}
ul {
list-style-type: disc;
}
ol li {
list-style: inside decimal;
}
.grey {background: #efefef; padding: 5px; border: 1px solid #000;}
JavaScript
var ItemViewModel = {
items: ko.observableArray([]),
addItem: function() { this.items.push({name: "new one"}); },
removeItem: function() { this.items.pop(); },
clearItems: function() { this.items.removeAll(); },
caller: function() { $('.grey').append('<li>called</li>') ; }
};
$('#clear_log').click(function(e) {
$(".grey").empty();
});
$(document).ready(function() {
ko.applyBindings(ItemViewModel);
});