LoginSignup
31
35

More than 5 years have passed since last update.

Knockout.jsで複数のViewModelを扱う

Last updated at Posted at 2014-09-03

結論:ネームスペースが別れるので、ViewModelはガンガン分割できる。

ViewModelを定義する

LTEとWiMAXの契約状態を表すモデルを作成

class LteViewModel
  constructor: ->
    @plan = ko.observable("")
    @status = ko.observable("")
class WimaxViewModel
  constructor: ->
    @plan = ko.obserbable("")
    @status = ko.obserbable("")

バインドする

$ ->
  lte_vm = new LteViewModel()
  wimax_vm = new WimaxViewModel()

  ko.applyBindings({
    lte: lte_vm,
    wimax: wimax_vm
  })

  # この後ajaxなりなんなりで各モデルのプロパティを操作する

applyBindingsでハッシュ的に複数のVMをバインド出来る

html側からのバインド

%div{data: {bind: "with: lte"}}
  %h3 LTEに関する契約情報
  %p{data: {bind: "text: plan"}}
  %p{data: {bind: "text: status"}}

%div{data: {bind: "with: wimax"}}
  %h3 WiMAXに関する契約情報
  %p{data: {bind: "text: plan"}}
  %p{data: {bind: "text: status"}}

結論

  • bind: withで名前空間が切れるので、プロパティ名はその内部で自由に設定できる。便利!

knockout.jsを使う意外なメリット

これはknockout.js以外のAngular等でも一緒なんですが、data-bind: ほげほげっていう記述を使うとXPATH指定で一意に特定できるので、TurnipなどのE2Eテストが書きやすくなります。

31
35
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
35