knockout.js データ群をforeachで出力
2012/04/10
ソース
- <!DOCTYPE html>
- <html lang="ja">
- <head>
- <meta charset="UTF−8">
- <title>knockoutjsちゅーとりある:データをテーブルにforeachで出力</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">
- $(function () {
- function SeatReservation(name, initialMeal) {
- var self = this;
- self.name = name;
- self.meal = ko.observable(initialMeal);
- }
- function ReservationsViewModel() {
- var self = this;
- self.availableMeals = [
- { mealName: "Standard (sandwich)", price: 0 },
- { mealName: "Premium (lobster)", price: 34.95 },
- { mealName: "Ultimate (whole zebra)", price: 290 }
- ];
- self.seats = ko.observableArray([
- new SeatReservation("Steve", self.availableMeals[0]),
- new SeatReservation("Bert", self.availableMeals[1])
- ]);
- }
- ko.applyBindings(new ReservationsViewModel());
- })();
- </script>
- </head>
- <body>
- <table>
- <thead><tr>
- <th>Passenger name</th><th>Meal</th><th>Surcharge</th>
- </tr></thead>
- <tbody data−bind="foreach: seats">
- <tr>
- <td data−bind="text: name"></td>
- <td data−bind="text: meal().mealName"></td>
- <td data−bind="text: meal().price"></td>
- </tr>
- </tbody>
- </table>
- </body>
- </html>
めも
tbodyでforeachする
- foreach(seats ~){
- ~tbodyの中身~
- }
上記のような感じで記述すべき内容は「knockout.js」だと下記のようにする。
「<tbody data−bind="foreach: seats">」にする。
これで「seats」を「foreach」する。
これで「seats」を「foreach」する。
meal()について
「meal().mealName」や「meal().price」は「SeatReservation()」で設定している「self.meal」と紐づく。
「self.meal」は「ReservationsViewModel()」で設定している「self.availableMeals」と紐づく。
HTML側の出力「meal.mealName」ではなく「meal().mealName」としているのは「meal」ってのが「observable」を使っていて、さらに「meal」ってのが配列?(オブジェクト?)だから。
「「knockout.js」の「Tutorial:Working with Lists and Collections」の「Step 1 of 5」」に詳細が記載されている。下記が原文。
Notice that, because the meal property is an observable, it’s important to invoke meal() as a function (to obtain its current value) before attempting to read sub-properties. In other words, write meal().price, not meal.price.
「self = this」について
今回のソースだと「this」を「self」にいれる必要ないと思う。
「function」内で「function」を使うときに「self = this」を利用ってのが多いらしい。
- function funcRe(){
- var self = this;
- function funcCatnap(){
- xxxSelf = self.xxx;
- xxxThis = this.xxx;
- }
- }
「funcCatnap()」内で「this」を使うと「funcCatnap()のthis」であって「funcRe()のthis」ではない。
「funcCatnap()」内で「funcRe()のthis」を使いたければ適当な変数に移しておく必要があるらしい。
「funcCatnap()」内で「funcRe()のthis」を使いたければ適当な変数に移しておく必要があるらしい。