如何使用 jQuery、RequireJS 和 KnockoutJS 创建基本的 TypeScript 项目 [英] How to create basic TypeScript project using jQuery, RequireJS, and KnockoutJS

查看:19
本文介绍了如何使用 jQuery、RequireJS 和 KnockoutJS 创建基本的 TypeScript 项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一个简单的操作方法,以使用 RequireJS、jQuery 和 KnockoutJS 创建 Visual Studio 2012 TypeScript 项目的最基本示例.有几个可用的例子,但对我来说有些比我想要的更复杂,所以我着手创建一个操作方法,并在此处发布以供公众审查.我已经回答了我自己的问题,作为问答式的知识共享练习.

对于那些不熟悉的人,这里是包含组件的快速细分...

TypeScript - 一种允许编写脚本的 Visual Studio 扩展通过作为 JavaScript 超集的语言创建 .TS 文件.这提供了定义与方法和变量相关联的数据类型的能力——否则 JavaScript 会缺少这些数据类型.通过这样做,编译时检查可以确保正确使用以尝试减少运行时冲突.在构建 Visual Studio 项目时,Visual Studio 扩展会将脚本编译为实际的 JavaScript.因此,这个扩展带有它自己的编译器 - tsc.exe.预计生成的 JavaScript 文件将部署到生产环境,而不是源代码 .ts 文件.

jQuery - 用于 HTML 文档遍历和操作、事件处理、动画和 Ajax 交互的 JavaScript 框架.>

RequireJS - 依赖加载器.有时 JavaScript 引用会变得疯狂.这试图帮助解决这些问题.我的示例表明,即使使用了许多 JavaScript 文件,HTML 也仅引用其中一个文件 - 加载其他文件的根 JavaScript 文件.

KnockoutJS - UI 绑定,使用 MVVM 模式.HTML 视图是指视图模型中的变量和方法.视图模型是一个 JavaScript 对象(JavaScript 文件可能是编译 .ts 文件的结果 - 请参阅上面的 TypeScript).

DefinitelyTyped - 还包括两个绝对类型的 NuGet 包.因为 TypeScript 试图验证数据类型的使用,所以它正在执行检查以确保它知道所有引用.JavaScript 比这更宽松一些.为了满足 TypeScript(在引用外部 JavaScript 对象时),我们需要一种方法来描述(向 TypeScript)我们期望使用的对象.这些DefinitelyTyped 脚本提供了这个定义.它们不提供任何功能,只是让 TypeScript 编译器清晰起来,以便它可以执行这些检查.

在下面的例子中,你会看到

///

这就是 TypeScript 编译器将如何包含 requirejs absoluteTyped 定义文件的方式.创建这些绝对类型脚本的组织已经创建了一个庞大的集合.这里我们只提到两个——KnockoutJS 和 RequireJS(嗯,因为这是本教程的范围)

解决方案

免责声明

本指南将展示使用 TypeScript、jQuery、KnockoutJS 和 RequireJS 构建基本网站的a" 方法.还有很多其他方法可以做到这一点.

入门

安装 Visual Studio 扩展

安装 Visual Studio 2012 扩展 - TypeScript for Microsoft Visual Studio 2012 PowerTool 1.0.1.0http://visualstudiogallery.msdn.microsoft.com/ac357f1e-9847-46ac-a4cf-5203

<小时>

创建新的 Visual Studio 项目

  • 启动 Visual Studio 2012.
  • 选择菜单项文件"->新建"->项目..."
  • 导航到模板"->其他语言"->TypeScript"(这实际上创建了一个扩展名为 .csproj 的项目文件 - 很奇怪)
  • 选择项目类型带有 TypeScript 的 HTML 应用程序"
<小时>

清理

从项目中删除文件 app.css、app.ts

<小时>

添加组件

使用 NuGet,添加...

  • RequireJS (我为本教程选择了 2.1.15 版)
  • KnockoutJS (我为本教程选择了 3.2.0 版)
  • jQuery (我为本教程选择了 2.1.1 版)
  • requirejs.TypeScript.DefinitelyTyped (我选择了 0.2.0 版
    本教程的 Jason Jarrett.它安装了一个打字稿 def 文件作者:Josh Baldwin - 版本 2.1.8 )
  • knockout.TypeScript.DefinitelyTyped (我选择了 0.5.7 版
    本教程的 Jason Jarrett)
<小时>

设置项目文件夹

在项目根目录创建项目文件夹

  • 申请
  • 模型
  • 视图模型
<小时>

创建一个基本的 TypeScript 模型

将 TypeScript 文件添加到项目文件夹Models"

  • 在解决方案资源管理器中右键单击文件夹模型"
  • 选择上下文菜单项添加"->新建项目..."
  • 在左侧窗格中,突出显示Visual C#"
  • 在右侧窗格中,突出显示TypeScript 文件"
  • 在文件名文本框中输入myTestModel.ts"点击添加"按钮

修改文件myTestModel.ts"

class myTestModel {公共字段Z:字符串;公共字段Y:字符串;公共字段X:数字;}出口=我的测试模型;

<小时>

创建一个 TypeScript 视图模型

将 TypeScript 文件添加到项目文件夹ViewModels"

  • 在解决方案资源管理器中右键单击文件夹ViewModels"
  • 选择上下文菜单项添加"->新建项目..."
  • 在左侧窗格中,突出显示Visual C#"
  • 在右侧窗格中,突出显示TypeScript 文件"
  • 在文件名文本框中,输入myViewModel.ts"
  • 点击添加"按钮

修改文件 myViewModel.ts...

///import myTestModel = require("Models/myTestModel");import ko = require("淘汰赛");类 myViewModel {public myString: KnockoutObservable;public myNumber: KnockoutObservable;public myComplexObject: KnockoutObservable;构造函数(){this.myString = ko.observable("一些测试数据");this.myNumber = ko.observable(987);var tempComplexObject = new myTestModel;tempComplexObject.fieldZ = "一些虚假的测试数据";tempComplexObject.fieldY = "另一个伪造的测试数据";tempComplexObject.fieldX = 123;this.myComplexObject = ko.observable(tempComplexObject);}myButton_Click() {alert("我被点击了");}}出口=我的视图模型;

<小时>

添加配置

添加RequireJS配置文件

  • 在解决方案资源管理器中右键单击项目文件夹应用程序"
  • 选择上下文菜单项添加"->新建项目..."
  • 在左侧窗格中,突出显示Visual C#"
  • 在右侧窗格中,突出显示TypeScript 文件"
  • 在文件名文本框中,输入require-config.ts"
  • 点击添加"按钮

修改文件require-config.ts"

///需要.配置({baseUrl: "",路径:{"jQuery": "脚本/jquery-2.1.1","knockout": "脚本/knockout-3.2.0.debug","myViewModel": "ViewModels/myViewModel"},垫片:{jQuery":{出口:$"}},});需要([jQuery"],函数($){$(document).ready(function () {require(["knockout", "myViewModel"], (knockout, myViewModel) => {var viewModel = new myViewModel;淘汰赛.applyBindings(viewModel);});});});

<小时>

修改现有文件 index.html

需要将视图与视图模型对齐.

<html lang="zh-cn"><头><meta charset="utf-8"/><title>TypeScript HTML 应用</title><script data-main="Application/require-config" src="Scripts/require.js"></script><身体><h1>TypeScript HTML 应用程序</h1><div id="myStringTest" data-bind="text: myString"></div><input id="myStringTest2" data-bind="value: myString"/><input id="myNumberTest" data-bind="value: myNumber"/><input id="myComplexObjectTest" data-bind="value: myComplexObject().fieldZ"/><button id="myMethodTest" data-bind="click: myButton_Click" >点击我</button>

<小时>

运行它

好的 - 是时候尝试一下了.完成,在 .ts 文件中设置一些断点,然后按 F5.

<小时>

结论:

如您所见,示例中的代码并不多.如果您运行该示例,然后单击按钮,您会发现 index.html 上的按钮绑定到 myViewModel.ts 中名为 myButton_Click 的方法.此外,文本框 myStringTest2 和 myNumberTest 绑定到视图模型中定义的变量.

require-config.ts 文件包含已连接的依赖项列表.knockout.applyBindings(viewModel)"这一行将 myViewModel 的实例与 html 视图相关联.

注意 TypeScript 如何允许使用数据类型声明变量?

我希望这本入门书能有所帮助.只需将几件作品放在桌子上就可以帮助我想象这些组件如何协同工作.KnockoutJS 有一些很酷的插件——比如knockout-mapping——它允许从Web 服务中提取的数据直接绑定到视图模型,无需中间转换或转换.此外,knockoutjs 可以支持模板化——大概是为了可以实现母版页.

为了完整起见,我将添加一个名为 Views 的项目文件夹,并将我的 html 保存在那里.我认为这对于 MVC/MVVM 开发来说更为传统.具有 .html 的 url 仍然困扰着我.我喜欢 MVC 风格的路由(没有文件扩展名),但这也很酷——尤其是因为它只不过是 HTML 和 JavaScript——真正的跨平台.除了 Web 服务调用(未包含在示例中)之外,没有回发,客户端处理速度很快.

请随时发表评论...

I have been searching for a simple how-to, to create the most basic example of a Visual Studio 2012 TypeScript project utilizing RequireJS, jQuery, and KnockoutJS. There are several examples available, but for me some where more complicated than I wanted so I set out to create a how-to, and have posted it here for public scrutiny. I have answered my own question as a Q&A style knowledge sharing exercise.

For those unfamiliar, here is a quick breakdown of the included components...

TypeScript - A Visual Studio extension that allows scripting to create a .TS file via a language that is a superset of JavaScript. This provides the ability to define a data type associated with methods and variables - which is otherwise missing from JavaScript. By doing so, compile time checks can ensure the proper use in an attempt to reduce run-time conflicts. When building the Visual Studio project, the Visual Studio extension will compile the script into actual JavaScript. As such, this extension comes with it's own compiler - tsc.exe. It is expected the resulting JavaScript files will be deployed to production, not the source code .ts files.

jQuery - a JavaScript framework for HTML document traversal and manipulation, event handling, animation, and Ajax interaction.

RequireJS - Dependency loader. Sometimes JavaScript references can get crazy. This attempts to assist with these concerns. My example shows that even though many JavaScript files are in use, the HTML only refers to one - the root JavaScript file that loads the others.

KnockoutJS - UI binding, utilizing the MVVM pattern. HTML views refer to variables and methods in a view-model. The view model is a JavaScript object (the JavaScript file is likely the result of compiling a .ts file - see TypeScript above).

DefinitelyTyped - Also included are two DefinitelyTyped NuGet packages. Because TypeScript is attempting to verify data type usage, it is performing a check to ensure it is aware of all references. JavaScript is a bit more loose than that. In order to satisfy TypeScript (when referring to external JavaScript objects) we need a way to describe (to TypeScript) the objects we expect to be used. These DefinitelyTyped scripts provide this definition. They provide no functionality, just clarity to the TypeScript compiler so it can perform these checks.

In the example below, you will see

/// <reference path="../Scripts/typings/requirejs/require.d.ts" />

This is how the TypeScript compiler will include the requirejs DefinitelyTyped definition file. The organization creating these DefinitelyTyped scripts have created a vast collection. Here we refer to only two - KnockoutJS, and RequireJS (well, because that is the scope of this tutorial)

解决方案

Disclaimer

This how-to will show "a" way to construct a basic website using TypeScript, jQuery, KnockoutJS, and RequireJS. There are many other ways to do it.

Getting Started

Install Visual Studio Extension

Install Visual Studio 2012 extension - TypeScript for Microsoft Visual Studio 2012 PowerTool 1.0.1.0 http://visualstudiogallery.msdn.microsoft.com/ac357f1e-9847-46ac-a4cf-520325beaec1


Create new Visual Studio Project

  • Start visual studio 2012.
  • Select menu item "File"->"New"->"Project..."
  • Navigate to "Templates"->"Other Languages"->"TypeScript" (this actually creates a project file with extension .csproj - weird)
  • Select Project Type "HTML Application with TypeScript"

Cleanup

Remove file app.css, app.ts from project


Add Components

Using NuGet, add...

  • RequireJS (I selected version 2.1.15 for this tutorial)
  • KnockoutJS (I selected version 3.2.0 for this tutorial)
  • jQuery (I selected version 2.1.1 for this tutorial)
  • requirejs.TypeScript.DefinitelyTyped (I selected version 0.2.0 by
    Jason Jarrett for this tutorial. it installed a typescript def file by Josh Baldwin - version 2.1.8 )
  • knockout.TypeScript.DefinitelyTyped (I selected version 0.5.7 by
    Jason Jarrett for this tutorial)

Setup Project Folders

Create project folders at root of project

  • Application
  • Models
  • ViewModels

Create a basic TypeScript model

Add TypeScript file to project folder "Models"

  • Right-click the folder "Models" in the Solution Explorer
  • select context menu item "Add"->"New Item..."
  • In left-hand pane, highlight "Visual C#"
  • In right-hand pane, highlight "TypeScript File"
  • In file name text box, enter "myTestModel.ts" Click button "Add"

Modify file "myTestModel.ts"

class myTestModel {
    public fieldZ: string;
    public fieldY: string;
    public fieldX: number;
}
export=myTestModel;


Create a TypeScript view-model

Add TypeScript file to project folder "ViewModels"

  • Right-click the folder "ViewModels" in the Solution Explorer
  • select context menu item "Add"->"New Item..."
  • In left-hand pane, highlight "Visual C#"
  • In right-hand pane, highlight "TypeScript File"
  • In file name text box, enter "myViewModel.ts"
  • Click button "Add"

Modify file myViewModel.ts...

/// <reference path="../Scripts/typings/knockout/knockout.d.ts" />

import myTestModel = require("Models/myTestModel");
import ko = require("knockout");

class myViewModel {
    public myString: KnockoutObservable<string>;
    public myNumber: KnockoutObservable<number>;
    public myComplexObject: KnockoutObservable<myTestModel>;

    constructor() {
        this.myString = ko.observable("some test data");
        this.myNumber = ko.observable(987);

        var tempComplexObject = new myTestModel;
        tempComplexObject.fieldZ = "some bogus test data";
        tempComplexObject.fieldY = "another bogus test data";
        tempComplexObject.fieldX = 123;

        this.myComplexObject = ko.observable(tempComplexObject);
    }

    myButton_Click() {
        alert("I was clicked");
    }
}
export=myViewModel;


Add configuration

Add RequireJS configuration file

  • Right-click project folder "Application" in the Solution Explorer
  • select context menu item "Add"->"New Item..."
  • In left-hand pane, highlight "Visual C#"
  • In right-hand pane, highlight "TypeScript File"
  • In file name text box, enter "require-config.ts"
  • Click button "Add"

Modify file "require-config.ts"

/// <reference path="../Scripts/typings/requirejs/require.d.ts" />

require.config({
    baseUrl: "",
    paths: {
        "jQuery": "Scripts/jquery-2.1.1",
        "knockout": "Scripts/knockout-3.2.0.debug",
        "myViewModel": "ViewModels/myViewModel"
    },
    shim: {
        "jQuery": {
            exports: "$"
        }
    },
});

require(["jQuery"], function ($) {
    $(document).ready(function () {
        require(["knockout", "myViewModel"], (knockout, myViewModel) => {
            var viewModel = new myViewModel;
            knockout.applyBindings(viewModel);
        });
    });
});


Modify existing file index.html

Need to align the view with the view model.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>TypeScript HTML App</title>
        <script data-main="Application/require-config" src="Scripts/require.js"></script>
    </head>
    <body>
        <h1>TypeScript HTML App</h1>

        <div id="myStringTest" data-bind="text: myString"></div>
        <input id="myStringTest2" data-bind="value: myString" />
        <input id="myNumberTest" data-bind="value: myNumber" />
        <input id="myComplexObjectTest" data-bind="value: myComplexObject().fieldZ" />
        <button id="myMethodTest" data-bind="click: myButton_Click" >click me</button>
    </body>
</html>


Run it

OK - time to give a try. Comple, set some breakpoints in the .ts files, and hit F5.


Conclusion:

As you can see, there is not a lot of code in the example. If you run the example, and click the button you will find the button on index.html is bound to a method in myViewModel.ts called myButton_Click. Also, the text box myStringTest2, and myNumberTest are bound to variables defined in the view model.

The require-config.ts file holds the list of dependencies that are wired up. The line "knockout.applyBindings(viewModel)" associates the instance of myViewModel with the html view.

Notice how TypeScript allows variables to be declared with a data type?

I hope this primer helps. Just laying the several pieces on the table helped me visualize how these components play together. KnockoutJS has some cool plug-ins - such as knockout-mapping - which allows data pulled from a web service to be directly bound to the view model with no intermediate transformation or translation. Also, knockoutjs can support templating - presumably so master pages can be implemented.

For completeness, I will add a project folder called Views, and hold my html there. I think that is more traditional for MVC/MVVM development. The url having .html is still nagging me. I like MVC-style routing (no file extensions), but this is pretty cool too - especially since its nothing more than HTML and JavaScript - truly cross platform. Aside from web services calls (not included in the example) there are no postbacks, client side processing is fast.

Please feel free to comment...

这篇关于如何使用 jQuery、RequireJS 和 KnockoutJS 创建基本的 TypeScript 项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆