Introduction

This blog demonstrates how to bind multiple view models with the knockout. Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.
Learn more from here http://knockoutjs.com/documentation/introduction.html
Download knockout.js from here http://knockoutjs.com/
The purpose of this blog is only to show how to bind multiple view models, so I am using mostly code from knockout.js.
So let's make a new asp.net website and add knockout.js.
  1. <head runat="server">
  2. <title></title>
  3. <script src="js/knockout-2.3.0.js"></script>
  4. </head>
In my code, I have two div
  1. <div id="EmployeeDiv">
  2. Choose a employee name:
  3. <select data-bind="options: employees, optionsCaption: 'Choose...', optionsText: 'name', value: chosenEmployee"></select>
  4. <button data-bind="enable: chosenEmployee, click: resetEmployee">Clear</button>
  5. <p data-bind="with: chosenEmployee">
  6. You have choosen <b data-bind="text: name"></b>
  7. ($<span data-bind="text: location"></span>)
  8. </p>
  9. </div>
  10. <div id="NameDiv">
  11. <p>First name: <strong data-bind="text: firstName"></strong></p>
  12. <p>Last name: <strong data-bind="text: lastName"></strong></p>
  13. <p>First name: <input data-bind="value: firstName" /></p>
  14. <p>Last name: <input data-bind="value: lastName" /></p>
  15. <button data-bind="click: capitalizeLastName">Go caps</button>
  16. <p>Full name: <strong data-bind="text: fullName"></strong></p>
  17. </div>
Now let's make view models
  1. <script>
  2. function EmployeesViewModel() {
  3. this.employees = [
  4. { name: "Nancy Davolio", location: "Seattle WA" },
  5. { name: "Andrew Fuller", location: "Tacoma WA" },
  6. { name: "Janet Leverling", location: "Kirkland WA" },
  7. { name: "Steven Buchanan", location: "London WA" },
  8. { name: "Margaret Peacock", location: "Redmond WA" }
  9. ];
  10. this.chosenEmployee = ko.observable();
  11. this.resetEmployee = function() {
  12. this.chosenEmployee(null)
  13. }
  14. }
  15. function AppViewModel() {
  16. this.firstName = ko.observable("Raj Kumar");
  17. this.lastName = ko.observable("Choudhary");
  18. this.capitalizeLastName = function() {
  19. var currentVal = this.lastName(); // Read the current value
  20. this.lastName(currentVal.toUpperCase()); // Write back a modified value
  21. };
  22. this.fullName = ko.computed(function() {
  23. return this.firstName() + " " + this.lastName();
  24. }, this);
  25. }
  26. // Activates knockout.js
  27. //ko.applyBindings(new EmployeesViewModel());
  28. //ko.applyBindings(new AppViewModel());
  29. ko.applyBindings(new EmployeesViewModel, document.getElementById("EmployeeDiv"));
  30. ko.applyBindings(new AppViewModel, document.getElementById("NameDiv"));
  31. </script>
Bold code shows how to bind multiple view models.
Let's run the application.
img1.jpg
Image 1.