LoginSignup
2
1

More than 5 years have passed since last update.

Knockoutでイベントハンドラーをバインドする

Posted at

ソースコード

alert.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-debug.js"></script>

<body>
    <button data-bind="click: showAlert">clickでalert表示</button>
    <script>
        ko.applyBindings({
            showAlert: () => alert('hello wrold!')
        })
    </script>
</body>

CDN

環境の準備を簡単にするため、KnockoutはCDN経由で取得します。

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-debug.js"></script>

binding

<button data-bind="click: showAlert">clickでalert表示</button>

htmlにViewModelのプロパティをバインドします。
data-bind属性で、イベント名と呼び出したい関数名を指定します。

ViewModelを適用

ko.applyBindings({
    showAlert: () => alert('hello wrold!')
})

ko.applyBindings関数にViewModelを渡します。
ViewModelはオブジェクトで構いません。

ViewModelに呼び出す関数showAlertを定義します。

関数の定義にアロー関数を使いましたが、定義方法は

{
    showAlert: function(){ alert('hello wrold!') }
}

でも

{
    showAlert(){ alert('hello wrold!') }
}

でも、構いません。

感想

データのバインドとイベントのバインドが同じ記法なのが不思議な感じです。

関連記事

Knockout.jsのHelloWorld

リンク

割と日本語のドキュメントが多いのに助かります。

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