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

Last updated at Posted at 2020-08-07

まとめ

挙動の追加

この例の最後に、最後の動作を追加してみましょう:"last name "の値を大文字にするボタンです。

ビューモデルの更新

まず、この動作を実装するために、viewmodelにcapitalizeLastName関数を追加します。

ViewModel
function AppViewModel() {
    // ... 変更しない。前回のコードは残す。

    this.capitalizeLastName = function() {
        var currentVal = this.lastName();        // Read the current value
        this.lastName(currentVal.toUpperCase()); // Write back a modified value
    };
}

注意!
観測可能な値を読み書きするには、関数として呼び出す必要がある。

ビューの更新
次に、クリックバインディングを使って、先ほど追加したビューモデル関数にクリックを関連付けるために、ボタンをビューに追加する。

View
<button data-bind="click: capitalizeLastName">Go caps</button>

コード

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

    this.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();    
    }, this);

    this.capitalizeLastName = function() {
        var currentVal = this.lastName();        // Read the current value
        this.lastName(currentVal.toUpperCase()); // Write back a modified value
    };    
}

// Activates knockout.js
ko.applyBindings(new AppViewModel());
View
<! -- これは *view* - UI の外観を定義する HTML マークアップです-->

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

<button data-bind="click: capitalizeLastName">Go caps</button>

コード解説

実際の画面

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?