Binding to specific array element Options
http://groups.google.com/group/knockoutjs/browse_thread/thread/c910d9d9b29253bf
by gurkavcu
HTML
<script src="https://github.com/downloads/SteveSanderson/knockout/jquery.tmpl.js"></script>
<div id="main">
<p data-id="1">9</p>
<p data-id="2">18</p>
<p data-id="3">32</p>
<p data-id="4">36</p>
</div>
<button onclick="updateText()">Update data text</button>
<button onclick="updateWithTemplate()">Update data with template</button>
<script id="priceTemplate" type="text/html">
<em>${id}</em>-$${price}
</script>
JavaScript
$(function() {
$.template('priceTmpl', $('#priceTemplate'));
});
function updateText() {
var updates = getFakeUpdates();
$.each(updates, function(index, value) {
$('p[data-id=' + value.id + ']').text(value.price);
});
};
function updateWithTemplate() {
var updates = getFakeUpdates();
$.each(updates, function(index, value) {
$('p[data-id=' + value.id + ']').html($.tmpl('priceTmpl', value));
});
};
function getFakeUpdates() {
return [{
id: Math.ceil(4 * Math.random()),
price: Math.ceil(100 * Math.random())
}, {
id: Math.ceil(4 * Math.random()),
price: Math.ceil(100 * Math.random())
}];
}