LoginSignup
6
6

More than 5 years have passed since last update.

Knockout.JSのmapping pluginを使う

Last updated at Posted at 2014-09-22

適当なAPIがJSONを返す際、mapping pluginを使うとViewModelの作成が楽になるのでメモ。

環境

Rails:4.0.3
gem:knockoutjs-rails

準備

application.js
//= require knockout
//= require knockout.mapping

これを追加するだけ。かんたん。

json

{
  name: 'Scott',
  children: [
    { id : 1, name : 'Alice' },
    { id : 2, name : 'Tarou'}
  ]
}

mappingとbindings

view_model = ko.mapping.fromJS("先ほどのJsonが入る")
ko.applyBindings(view_model)

Viewから使う

%h3{data: {bind: 'text: name'}}
%ul{data: {bind: 'foreach: children'}} Children
  %li{data: {bind: 'text: id'}}
  %li{data: {bind: 'text: name'}}

まとめ

データ構造がそのままViewModelになり、かつ、各要素はbinding済みになる。ko.computed等込み入ったことがやりたい場合は幾つか方法があるみたいなので次回。

6
6
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
6
6