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チュートリアル3

Last updated at Posted at 2020-06-20

まとめ

  • 複数の観測可能な値を組み合わせ、変換して他の値を作成したい場合はcomputedプロパティを使用する。

  • 具体的にはcomputedプロパティにコールバック関数を渡す。Viewにマークアップを追加しUIの値を渡す。

計算値の定義

  • 複数の観測可能な値を組み合わせたい場合
  • 変換して他の値を作成したい場合
  • この例では、フルネームをファーストネーム+スペース+ラストネームと定義したい場合

これを処理するために、Knockoutにはcomputedプロパティという概念があります。これは、観測可能な(変更時に通知される)プロパティであり、他の観測可能な値に基づいて計算されます。

問題

firstName と lastName が宣言された後
AppViewModel 内に以下のコードを追加して、ビューモデルに fullName プロパティを追加します。

ViewModel
this.fullName = ko.computed(function() {
  return this.firstName() + " " + this.lastName();    
}, this);
ViewModel
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
  this.firstName = ko.observable("Bert");
  this.lastName = ko.observable("Bertington"); 
    
  this.fullName = ko.computed(function() {
    return this.firstName() + " " + this.lastName();
  }, this);
}

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

コード解説
値の計算方法を指定するコールバック関数をko.computedに渡す。
次に、ビューの下部にマークアップを追加して、UIにfullName値を表示する。
コールバック関数とは?

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>

<p>Full name: <strong data-bind="text: fullName"></strong></p>

実際の画面

Screenshot from Gyazo

参考にした記事(いつもありがとうございます。)

http://learn.knockoutjs.com/#/?tutorial=intro

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?