selected object pattern with knockout

http://stackoverflow.com/questions/8788543/selected-object-pattern-with-knockout

by Valerie Ren

HTML

<script src="http://knockoutjs.com/downloads/knockout-2.0.0.debug.js"></script>
<div id="content">
    <div data-bind="with: selected_item">
        <h3 data-bind="text : name"></h3>    
    </div>
    <hr/>    
    
    <ul>
    <!-- ko foreach: myViewModel.items -->
    <li  data-bind="text : name"/>
    <!-- /ko -->
    </ul>  
</div>

JavaScript

var Item = function(id, name) {
    this.id = id;
    this.name = name;
};

myViewModel = {
    items: ko.observableArray([new Item(1, "one"), new Item(2, "two")]),
    selected_item: ko.observable()
};

$("#content").on("click", "li", function(e) {
    var item = ko.dataFor(this),
        current = myViewModel.selected_item;

    if (!current() || item.id !== current().id) {
        current(item);
    }
});
    
ko.applyBindings(myViewModel);