Write some code

Write some code

Let’s write our first TypeScript file using Knockout. First, create a new file in your src directory named hello.ts.

import * as ko from "knockout";

class HelloViewModel {
  language: KnockoutObservable<string>
  framework: KnockoutObservable<string>

  constructor(language: string, framework: string) {
    this.language = ko.observable(language);
    this.framework = ko.observable(framework);
  }
}

ko.applyBindings(new HelloViewModel("TypeScript", "Knockout"));

Next, we’ll create a file named require-config.ts in src as well.

declare var require: any;
require.config({
  paths: {
    "knockout": "externals/knockout-3.4.0",
  }
});

This file will tell RequireJS where to find Knockout when we import it, just like we did in hello.ts. Any page that you create should include this immediately after RequireJS, but before importing anything else. To get a better understanding of this file and how to configure RequireJS, you can read up on its documentation.

We’ll also need a view to display our HelloViewModel. Create a file at the root of proj named index.html with the following contents:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello Knockout!</title>
  </head>
  <body>
    <p>
      Hello from
      <strong data-bind="text: language">todo</strong>
      and
      <strong data-bind="text: framework">todo</strong>!
    </p>

    <p>Language: <input data-bind="value: language" /></p>
    <p>Framework: <input data-bind="value: framework" /></p>

    <script src="./externals/require.js"></script>
    <script src="./built/require-config.js"></script>
    <script>
      require(["built/hello"]);
    </script>
  </body>
</html>

Notice there are three script tags. First, we’re including RequireJS itself. Then we’re mapping the paths of our external dependencies in require-config.js so that RequireJS knows where to look for them. Finally, we’re calling require with a list of modules we’d like to load.

doc_TypeScript
2016-10-04 19:25:46
Comments
Leave a Comment

Please login to continue.