LoginSignup
1

More than 5 years have passed since last update.

Knockout.jsのHelloWorld

Last updated at Posted at 2016-04-12

Knockoutを使って画面に要素を表示します。

スクリーンショット

スクリーンショット 2016-04-12 10.01.21.png

hello wrold!を表示します。

ソースコード

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

<body>
    <span data-bind="text: message"></span>
    <script>
        ko.applyBindings({
            message: 'hello wrold!'
        });
    </script>
</body>

CDN

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

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

binding

<span data-bind="text: message"></span>

htmlにViewModelのプロパティをバインドします。
data-bind属性で、バインド先の属性名とバインドするプロパティ名を指定します。

ViewModelを適用

ko.applyBindings({
    message: 'hello wrold!'
});

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

ViewModelにバインドするプロパティmessageを定義します。

感想

ここまでだとhtmlの属性で書く、変わった記法のテンプレートエンジンに見えます。

関連記事

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

リンク

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

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
1