<div class="person-editor"> <h3>Person</h3> <p>First name: <input class="first-name" /></p> <p>Last name: <input class="last-name" /></p> </div> <div id="weather-list"> <h3>Weather</h3> <table> <thead><tr><th>City name</th><th>Temperature</th></tr></thead> <tbody class="cities-list"> <tr> <td class="city"></td> <td class="temp"></td> </tr> </tbody> </table> <button class="add-city">Add city</button> </div>
function personModel() { this.firstName = ko.observable("Bert"); this.lastName = ko.observable("Bertington"); } function weatherModel() { this.cities = ko.observableArray([ { city: "London", temperature: 22 }, { city: "Paris", temperature: 26 } ]); this.addItem = function() { this.cities.push({ city: "New city", temperature: "Something" }) } } function appViewModel() { this.person = new personModel(); this.weather = new weatherModel(); }; var myViewModel = new appViewModel(); // This syntax would be way more succinct with CoffeeScript ko.bindingConventions.conventions(".person-editor", { ".person-editor" : { 'with': myViewModel.person }, ".first-name" : function(person) { return { value: person.firstName } }, ".last-name" : function(person) { return { value: person.lastName } } }); ko.bindingConventions.conventions("#weather-list", { "#weather-list" : { 'with': myViewModel.weather }, ".cities-list" : function(weather) { return { foreach: weather.cities } }, ".city" : function(item) { return { text: item.city } }, ".temp" : function(item) { return { text: item.temperature } }, ".add-city" : { click: function() { this.addItem() } } }); ko.applyBindings(myViewModel);