Getting Started With
Knockout.js
2013/07/27 Sapporo.js
@iakio
• 石田朗雄
• 普段は主にPHPを書いてます
• Knockout.jsは2011年にちょっと使ってみた程度
今日話さないこと
• MVCとかMVVMってなに?
• 説明できません
• リアクティブプログラミングってなに?
• 興味あるかたは調べてみましょう
Knockout.jsとは
• Backbone.js, Ember.js, Angular.jsの次くらいに流
行っているのかも
• Ember.js, Angular.jsと比べるとかなり小さい
• Knockout.jsはフレームワークではなくライブラ
リだ(ズギャーン
• たぶん最も特徴的なのはDependency Tracking
Knockout.jsのはじめかた
• 公式のチュートリアルを2つくらいやる
• APIを3,4個学ぶ
• Bindingを5から10個くらい学ぶ
• とりあえずそれくらい
それでなにをやりたいの
• 本来書きたいことに集中したい
• 変更の頻度が違うものは分けたい
理想
• JavaScriptの状態(プロパティ)が変更されたら、
自動的に見た目も変更されるといいなあ
• ブラウザ上でテキストボックスやドロップダウ
ンを操作すると自動的にJavaScriptの状態に反
映されるといいなあ
Getter/Setter
{{price}} this.set(‘price’, 100);
this.get(‘price’); Ember.js
<p data-bind=“text:price”>
</p>又は
<!-- ko text: price -->
<!-- /ko -->
this.price = ko.observable();
this.price(100);
this.price();
Knockout.js
{{price}} $scope.price = 100;
$scope.price; Angular.js
DEMO
Dependency Tracking
Total = price * quantity
jQuery
イベントが発生したら、PriceとQuantityを取得し
てTotalを書き換える
$(“#quantity,#price”).on(“change”, function () {
$(“#total”).text(
$(“#price”).text() * $(“#quantity”).text();
);
});
jQuery
Totalはpriceとquantityから求められる
total: function () {
return this.get(‘price’) * this.get(‘quantity’);
}.property(‘price’, ‘quantity’);
Ember.js
this.total = ko.computed(function () {
return this.price() * this.quantity();
}, this);
Knockout.js
すこしだけ仕組みについて
• 定義された時点で一回呼んでみる
• その間に呼ばれたGetterに依存している
• total()「今からトータル計算しまーす」
• price()「ん?トータル計算中に呼ばれた!」
• quantity()「ん?トータル計算中に呼ばれた!」
• price(100)「よーしtotal()再計算しちゃうぞー」
this.total = ko.computed(function () {
return this.price() * this.quantity();
}, this);
Knockout.js
こういう場合は
• 初回にflagが偽だとpriceとquantityが呼ばれな
いので依存関係が記録されない
this.total = ko.computed(function () {
if (this.flag) {
return this.price() * this.quantity();
} else { … }
}, this);
Knockout.js
こうする
• 初回、priceとquantityの依存関係が記録されないが、
flagは記録されている
• flagが真になるとtotalが呼ばれ、priceとquantityの
依存関係が記録される
this.flag = ko.observable();
this.total = ko.computed(function () {
if (this.flag()) {
return this.price() * this.quantity();
} else { … }
}, this);
Knockout.js
考え方を変える
• 例えばページャやフィルタ
• 「次へ」を押されたら、ページ番号を+1する
• ページ番号に依存して
• 現ページに表示するアイテムが変わる
• 「前へ」「次へ」ボタンを表示するかが変わる
• その他色々が自動的に変わる
良いところ
• 小さい。覚えることが少ない
• ViewModelは単なるObject
• ModelとかControllerとかいう言葉がでてこない
• セレクタから解放される
• 本来書きたかったことに集中できる
• Tutorialがよくできている
注意点
• 全部入りではない
• AjaxしたければjQueryを使う
• Routerが必要であればsammy.jsを使う
• その他Pluginなどあるが、そこまでやるか
• 多対一のような複雑なdependency
• メソッド重複して呼ばれないよう注意
• ViewModelの肥大化
• 使いどころを選ぶ
• SEOってなんだったっけ
• Progressive Enhancement?
Resources
• http://knockoutjs.com
• http://knockmeout.net
• http://blog.stevensanderson.com

Getting start with knockout.js