0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Knockout.jsチュートリアル2

Last updated at Posted at 2020-06-20

データを編集可能にする

静的なデータを表示するだけではありません。
データの編集も可能です。
通常の HTML コントロールと一緒に値のバインディングを使用する。

以下のマークアップコードをビューの下部に追加する(既存のマークアップはその上の場所に残す)。

View
<!-- This is a *view* - HTML markup that defines the appearance of your UI -->

<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
ViewModel
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
    this.firstName = "Bert";
    this.lastName = "Bertington";
}

// Activates knockout.js
ko.applyBindings(new AppViewModel());

アプリケーションを実行してください。

  • テキストボックスの一つでテキストを編集してみる
  • しかし何も起こらないようです。これを修正してみましょう...。

オブザーバブルの紹介

実際にテキストボックスを編集すると、その下にあるビューモデルのデータが更新されます。
しかし、ビューモデルのプロパティは単なるJavaScriptの文字列であるため、変更されたことを通知する手段がないため、UIは静的なままです。
そのため、Knockout には observables という概念があり、値が変更されたときに自動的に通知を発行するプロパティです。

ko.observable を使用して、viewmodel を更新して firstName と lastName プロパティを observable にします。

ViewModel

//function AppViewModel() {
//    this.firstName = "Bert";
//    this.lastName = "Bertington";
//}

//編集

function AppViewModel() {
    this.firstName = ko.observable("Bert");
    this.lastName = ko.observable("Bertington");
}

// Activates knockout.js
ko.applyBindings(new AppViewModel());

実際の画面

Screenshot from Gyazo

参考にしたサイト(いつもありがとうございます)

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?