LoginSignup
1
3

More than 5 years have passed since last update.

TypeScriptでKnockout!!

Last updated at Posted at 2018-03-29

TypeScriptでKnockoutを使ってみます。
ただし、下記コマンドが実行できる前提です。
- npm
- tsc
- typings

環境構築

今回はVisual Studioを使わず、testフォルダ内にサンプルを作ってみます。

testフォルダで下記コマンドを実行し、tsc、typings、npmを実行出来る環境を用意します。

tsc --init
typings init
npm init

型定義ファイルの取得

型定義ファイルを取得しましょう。

今回はKnockoutの型定義ファイルを取得します。

typings install dt~knockout --global --save

knockout.jsの取得

npmでknockout.jsを取得します。

npm install knokcout 

サンプル実装

まず、ViewModelを作ります。

viewModel.ts

/// <reference path="../typings/index.d.ts"/>

class ViewModel{
    // property
    private privateMsg = "隠しメッセージ";

    // ko observable
    private observableMsg = ko.observable("");

    constructor(){
        // ko observableに値をセット
        this.observableMsg("Hello Knockout World!!!");
    }

    /**
     * 隠しメッセージを表示します。
     */
    private showMsg(): void{
        alert(this.privateMsg);
    }
}

次に、ViewModelをバインドします。

app.ts

/// <reference path="../typings/index.d.ts"/>
/// <reference path="viewModel.ts"/>

window.onload = function(){
    const viewModel = new ViewModel();
    ko.applyBindings(viewModel);
}

画面を作ります。

node_moduleを直に参照するのは。。。

index.html

<html>
    <head>
        <script src="node_modules/knockout/build/output/knockout-latest.js"></script>
        <script src="ts/viewModel.js"></script>
        <script src="ts/app.js"></script>
    </head>
    <body>
        <div data-bind="text: observableMsg"></div>
        <button type="button" data-bind="click: showMsg">メッセージを表示する</button>
    </body>
</html>

tsのトランスパイル

tsファイルをjsファイルにトランスパイルします。

tsc app.ts
tsc viewModel.ts

今回は手動でトランスパイルしましたが、gulpやらgruntで自動化するのが望ましいです。

そもそもVisual Studio使えばこんな面倒なことしなくても

画面の表示

早速画面を表示しましょう。

typescript_knockout_index.png

ボタンをクリックするとViewModelで定義した関数が呼び出されます。

typescript_knockout_index_clicked.png

サンプルの構成

typescript_knockout_constitution.png

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