Advertisement

Getting start with knockout.js

Programmer
Jul. 28, 2013
Advertisement

More Related Content

Slideshows for you(20)

Advertisement

Getting start with knockout.js

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