knockoutjsちゅーとりある:データ件数によって処理を変える
- <!DOCTYPE html>
- <html lang="ja">
- <head>
- <meta charset="UTF-8">
- <title>knockoutjsちゅーとりある:データ件数によって処理を変える</title>
- <script type="text/javascript" src="jquery-1.5.1.min.js"></script>
- <script type="text/javascript" src="knockout-2.1.0beta.js"></script>
- <script type="text/javascript">
- $(document).ready(function () {
- // 表示部
- function SeatReservation(name, initialMeal) {
- var self = this;
- // data-bindの各ラベル?に対応する値の設定
- self.name = name;
- self.meal = ko.observable(initialMeal);
- // 「price」がfalseの時は「None」と表示させる
- self.formattedPrice = ko.computed(function() {
- var price = self.meal().price;
- return price ? "$" + price.toFixed(2) : "None";
- });
- }
- // ko.applyBindings()が呼ばれたときに実行される
- function ReservationsViewModel() {
- var self = this;
- // データ
- self.availableMeals = [
- { mealName: "Standard (sandwich)", price: 0 },
- { mealName: "Premium (lobster)", price: 34.95 },
- { mealName: "Ultimate (whole zebra)", price: 290 }
- ];
- // 最初に表示するデータ(<table>の<tbody>のdata-bindのラベル?が「seats」の中身)
- self.seats = ko.observableArray([
- new SeatReservation("Steve", self.availableMeals[0]),
- new SeatReservation("Bert", self.availableMeals[0])
- ]);
- // Priceの総額
- self.totalSurcharge = ko.computed(function() {
- var total = 0;
- for (var i = 0; i < self.seats().length; i++)
- {
- total += self.seats()[i].meal().price;
- }
- return total;
- });
- // 「Reserve another seat」をクリックしたときpush()する
- self.addSeat = function() {
- self.seats.push(new SeatReservation("", self.availableMeals[0]));
- }
-
- // 「Remove」をクリックしたときremove()する
- self.removeSeat = function(seat) {
- self.seats.remove(seat)
- }
-
- }
- ko.applyBindings(new ReservationsViewModel());
- })();
- </script>
- </head>
- <body>
- <h2>Your seat reservations (<span data-bind="text: seats().length"></span>)</h2>
- <table>
- <thead><tr>
- <th>Passenger name</th><th>Meal</th><th>Surcharge</th><th></th>
- </tr></thead>
- <tbody data-bind="foreach: seats">
- <tr>
- <td><input data-bind="value: name" /></td>
- <td><select data-bind="options: $root.availableMeals, value: meal, optionsText: 'mealName'"></select></td>
- <td data-bind="text: formattedPrice"></td>
- <td><a href="#" data-bind="click: $root.removeSeat">Remove</a></td>
- </tr>
- </tbody>
- </table>
- <button data-bind="click: addSeat, enable: seats().length < 5">Reserve another seat</button>
- <h3 data-bind="visible: totalSurcharge() > 0">
- Total surcharge: $<span data-bind="text: totalSurcharge().toFixed(2)"></span>
- </h3>
- <div style="font-size:10pt;text-align:right;margin-top:0.5em;">
- <a href="//tips.recatnap.info/" target="_top">PCスキルの小技・忘却防止メモ</a> -
- <a href="//tips.recatnap.info/wiki/" target="_top">PCスキルの小技・忘却防止メモのまとめ(wiki)</a>
- </div>
- <div style="font-size:10pt;text-align:center;margin-top:0.5em;padding:0.5em;border-top:1px solid #ccc;">
- Copyright © 2009 by PCスキルの小技・忘却防止メモ. All rights reserved.
- </div>
- </body>
- </html>