일종의 TypeScript, Knockout, 탄생!!

5040 단어 TypeScriptknockoutjs
TypeScript를 사용하여 Knockout을 사용해 보십시오.
그러나 전제 조건은 다음과 같은 명령을 실행할 수 있다는 것이다.
- npm
- tsc
- typings

환경 구조


이번에는 Visual Studio를 사용하지 않고 테스트 폴더에서 샘플을 만들어 보았습니다.
테스트 폴더에서 다음 명령을 실행하고 tsc, typings, npm를 실행할 수 있는 환경을 준비합니다.
tsc --init
typings init
npm init

형식 정의 파일 가져오기


형식 정의 파일을 가져옵니다.
이번에는 Knockout의 형식 정의 파일을 가져옵니다.
typings install dt~knockout --global --save

knockout.자격을 취득하다


npm에서 knockout.얻다
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_모듈을 직접 참조하는 건...
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
이번에는 수동으로 움직여서 글로프와 grunt를 통해 자동화되기를 바랍니다.
원래 Visual Studio를 사용하면 이렇게 귀찮게 할 필요가 없어요.

화면 표시


화면 바로 띄워주세요.

버튼을 클릭하면 ViewModel에서 정의한 함수가 호출됩니다.

샘플의 구성


좋은 웹페이지 즐겨찾기