ソースコード
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!') }
}
でも、構いません。
感想
データのバインドとイベントのバインドが同じ記法なのが不思議な感じです。
関連記事
リンク
割と日本語のドキュメントが多いのに助かります。