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><span class="price" data-id="1">9</span>  <span class="status" data-id="1"></span></p>
    <p><span class="price" data-id="2">18</span>  <span class="status" data-id="2"></span></p>
    <p><span class="price" data-id="3">32</span>  <span class="status" data-id="3"></span></p>
    <p><span class="price" data-id="4">36</span>  <span class="status" data-id="4"></span></p>
</div>

<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 updateWithTemplate() {
    var updates = getFakeUpdates();

    $.each(updates, function(index, value) {
        $('span.price[data-id=' + value.id + ']').html($.tmpl('priceTmpl', value));
        if (value.price > 50) {
            $('span.status[data-id=' + value.id + ']').html('invalid');
        }
        else {
            $('span.status[data-id=' + value.id + ']').html('');
        }
    });
};

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())
    }];
}