knockoutjsちゅーとりある:データをテーブルに出力して、編集可能にする

  1. <!DOCTYPE html>
  2. <html lang="ja">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>knockoutjsちゅーとりある:データをテーブルに出力して、編集可能にする</title>
  6. <script type="text/javascript" src="jquery-1.5.1.min.js"></script>
  7. <script type="text/javascript" src="knockout-2.1.0beta.js"></script>
  8. <script type="text/javascript">
  9.   $(function () {
  10.     function SeatReservation(name, initialMeal) {
  11.       var self = this;
  12.       self.name = name;
  13.       self.meal = ko.observable(initialMeal);
  14.       
  15.       self.formattedPrice = ko.computed(function() {
  16.         var price = self.meal().price;
  17.         return price ? "$" + price.toFixed(2) : "None";
  18.       });  
  19.     }
  20.     function ReservationsViewModel() {
  21.       var self = this;
  22.       self.availableMeals = [
  23.         { mealName: "Standard (sandwich)",    price: 0 },
  24.         { mealName: "Premium (lobster)",      price: 34.95 },
  25.         { mealName: "Ultimate (whole zebra)", price: 290 }
  26.       ];
  27.       self.seats = ko.observableArray([
  28.         new SeatReservation("Steve", self.availableMeals[0]),
  29.         new SeatReservation("Bert",  self.availableMeals[1])
  30.       ]);
  31.       self.addSeat = function() {
  32.         self.seats.push(new SeatReservation("", self.availableMeals[0]));
  33.       }
  34.     }
  35.     ko.applyBindings(new ReservationsViewModel());
  36.   })();
  37. </script>
  38. </head>
  39. <body>
  40. <table>
  41. <thead><tr>
  42.   <th>Passenger name</th><th>Meal</th><th>Surcharge</th>
  43. </tr></thead>
  44. <tbody data-bind="foreach: seats">
  45. <tr>
  46.   <td><input data-bind="value: name" /></td>
  47.   <td><select data-bind="options: $root.availableMeals, value: meal, optionsText: 'mealName'"></select></td>
  48.   <td data-bind="text: formattedPrice"></td>
  49. </tr>
  50. </tbody>
  51. </table>
  52. <button data-bind="click: addSeat">Reserve another seat</button>
  53. <div style="font-size:10pt;text-align:right;margin-top:0.5em;">
  54. <a href="//tips.recatnap.info/" target="_top">PCスキルの小技・忘却防止メモ</a> -
  55. <a href="//tips.recatnap.info/wiki/" target="_top">PCスキルの小技・忘却防止メモのまとめ(wiki)</a>
  56. </div>
  57. <div style="font-size:10pt;text-align:center;margin-top:0.5em;padding:0.5em;border-top:1px solid #ccc;">
  58. Copyright &copy; 2009 by PCスキルの小技・忘却防止メモ. All rights reserved.
  59. </div>
  60. </body>
  61. </html>