Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Knockout.JSのmapping pluginを使う

More than 5 years have passed since last update.

適当な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等込み入ったことがやりたい場合は幾つか方法があるみたいなので次回。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away