Knockout - Select from a UL

by Kevin McIsaac

HTML

<ul data-bind="foreach: people">
<li data-bind="text:name, click:$parent.selectPerson"></li>
</ul>

<div data-bind="with:selectedPerson">
<span data-bind="text:id"></span>
<input data-bind="value:name"/>
<input data-bind="value:country"/>
</div>

JavaScript

var Person = function(id, name, country) {
    var self = this;
    self.id = ko.observable(id);
    self.name = ko.observable(name);
    self.country = ko.observable(country);
    return self;
};

var vm = (function() {
    var people = ko.observableArray(),
        selectedPerson = ko.observable(),
        getPeople = function() {
            people.push(new Person(1, 'John', 'USA'));
            people.push(new Person(2, 'Mike', 'UK'));
            people.push(new Person(3, 'Dan', 'AUS'));
        },
        selectPerson = function(p){
            selectedPerson(p);
        };
    getPeople();

    return {
        people: people,
        selectedPerson: selectedPerson,
        selectPerson : selectPerson 
    };
})();

console.log(vm);

ko.applyBindings(vm);