简体   繁体   English

如何使用jQuery,RequireJS和KnockoutJS创建基本的TypeScript项目

[英]How to create basic TypeScript project using jQuery, RequireJS, and KnockoutJS

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. 我一直在寻找一个简单的操作方法,使用RequireJS,jQuery和KnockoutJS创建Visual Studio 2012 TypeScript项目的最基本示例。 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. TypeScript - 一种Visual Studio扩展,允许脚本通过JavaScript的超集语言创建.TS文件。 This provides the ability to define a data type associated with methods and variables - which is otherwise missing from JavaScript. 这提供了定义与方法和变量相关联的数据类型的能力 - 否则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. 构建Visual Studio项目时,Visual Studio扩展会将脚本编译为实际的JavaScript。 As such, this extension comes with it's own compiler - tsc.exe. 因此,这个扩展附带了它自己的编译器--tsc.exe。 It is expected the resulting JavaScript files will be deployed to production, not the source code .ts files. 预计生成的JavaScript文件将部署到生产环境,而不是源代码.ts文件。

jQuery - a JavaScript framework for HTML document traversal and manipulation, event handling, animation, and Ajax interaction. jQuery - 用于HTML文档遍历和操作,事件处理,动画和Ajax交互的JavaScript框架。

RequireJS - Dependency loader. RequireJS - 依赖加载器。 Sometimes JavaScript references can get crazy. 有时JavaScript引用会变得疯狂。 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. 我的示例显示,即使使用了许多JavaScript文件,HTML也只引用一个 - 加载其他文件的根JavaScript文件。

KnockoutJS - UI binding, utilizing the MVVM pattern. KnockoutJS - 利用MVVM模式进行UI绑定。 HTML views refer to variables and methods in a view-model. HTML视图引用视图模型中的变量和方法。 The view model is a JavaScript object (the JavaScript file is likely the result of compiling a .ts file - see TypeScript above). 视图模型是一个JavaScript对象(JavaScript文件可能是编译.ts文件的结果 - 请参阅上面的TypeScript)。

DefinitelyTyped - Also included are two DefinitelyTyped NuGet packages. DefinitelyTyped - 还包括两个DefinitelyTyped NuGet包。 Because TypeScript is attempting to verify data type usage, it is performing a check to ensure it is aware of all references. 由于TypeScript正在尝试验证数据类型的使用情况,因此它正在执行检查以确保它知道所有引用。 JavaScript is a bit more loose than that. JavaScript比这更松散。 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. 为了满足TypeScript(当引用外部JavaScript对象时),我们需要一种方法来描述(对TypeScript)我们期望使用的对象。 These DefinitelyTyped scripts provide this definition. 这些DefinitelyTyped脚本提供了此定义。 They provide no functionality, just clarity to the TypeScript compiler so it can perform these checks. 它们不提供任何功能,只是TypeScript编译器的清晰度,因此它可以执行这些检查。

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. 这就是TypeScript编译器将包含requirejs DefinitelyTyped定义文件的方式。 The organization creating these DefinitelyTyped scripts have created a vast collection. 创建这些DefinitelyTyped脚本的组织创建了一个庞大的集合。 Here we refer to only two - KnockoutJS, and RequireJS (well, because that is the scope of this tutorial) 这里我们只提到两个 - KnockoutJS和RequireJS(好吧,因为这是本教程的范围)

Disclaimer 放弃

This how-to will show "a" way to construct a basic website using TypeScript, jQuery, KnockoutJS, and RequireJS. 该方法文档将显示使用TypeScript,jQuery,KnockoutJS和RequireJS构建基本网站的“方法 There are many other ways to do it. 还有很多其他方法可以做到这一点。

Getting Started 入门

Install Visual Studio Extension 安装Visual Studio扩展

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 安装Visual Studio 2012扩展 - 适用于Microsoft Visual Studio 2012 PowerTool 1.0.1.0的TypeScript http://visualstudiogallery.msdn.microsoft.com/ac357f1e-9847-46ac-a4cf-520325beaec1


Create new Visual Studio Project 创建新的Visual Studio项目

  • Start visual studio 2012. 启动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) 导航到“ 模板 ” - >“ 其他语言 ” - >“ TypeScript ”(这实际上创建了一个扩展名为.csproj的项目文件 - 很奇怪)
  • Select Project Type "HTML Application with TypeScript" 选择项目类型“使用TypeScript的HTML应用程序”

Cleanup 清理

Remove file app.css, app.ts from project 从项目中删除文件app.css,app.ts


Add Components 添加组件

Using NuGet, add... 使用NuGet,添加...

  • RequireJS (I selected version 2.1.15 for this tutorial) RequireJS (我为本教程选择了2.1.15版本)
  • KnockoutJS (I selected version 3.2.0 for this tutorial) KnockoutJS (我为本教程选择了3.2.0版本)
  • jQuery (I selected version 2.1.1 for this tutorial) jQuery (我为本教程选择了2.1.1版本)
  • requirejs.TypeScript.DefinitelyTyped (I selected version 0.2.0 by requirejs.TypeScript.DefinitelyTyped (我选择版本0.2.0 by
    Jason Jarrett for this tutorial. Jason Jarrett为本教程。 it installed a typescript def file by Josh Baldwin - version 2.1.8 ) 它安装了Josh Baldwin的打字稿def文件 - 版本2.1.8)
  • knockout.TypeScript.DefinitelyTyped (I selected version 0.5.7 by knockout.TypeScript.DefinitelyTyped (我选择版本0.5.7 by
    Jason Jarrett for this tutorial) Jason Jarrett为本教程)

Setup Project Folders 设置项目文件夹

Create project folders at root of project 在项目的根目录下创建项目文件夹

  • Application 应用
  • Models 楷模
  • ViewModels 的ViewModels

Create a basic TypeScript model 创建一个基本的TypeScript模型

Add TypeScript file to project folder "Models" 将TypeScript文件添加到项目文件夹“Models”

  • Right-click the folder "Models" in the Solution Explorer 在解决方案资源管理器中右键单击“模型”文件夹
  • select context menu item "Add"->"New Item..." 选择上下文菜单项“添加” - >“新项目...”
  • In left-hand pane, highlight "Visual C#" 在左侧窗格中,突出显示“Visual C#”
  • In right-hand pane, highlight "TypeScript File" 在右侧窗格中,突出显示“TypeScript文件”
  • In file name text box, enter "myTestModel.ts" Click button "Add" 在文件名文本框中,输入“myTestModel.ts”单击“添加”按钮

Modify file "myTestModel.ts" 修改文件“myTestModel.ts”

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

Create a TypeScript view-model 创建TypeScript视图模型

Add TypeScript file to project folder "ViewModels" 将TypeScript文件添加到项目文件夹“ViewModels”

  • Right-click the folder "ViewModels" in the Solution Explorer 在解决方案资源管理器中右键单击“ViewModels”文件夹
  • select context menu item "Add"->"New Item..." 选择上下文菜单项“添加” - >“新项目...”
  • In left-hand pane, highlight "Visual C#" 在左侧窗格中,突出显示“Visual C#”
  • In right-hand pane, highlight "TypeScript File" 在右侧窗格中,突出显示“TypeScript文件”
  • In file name text box, enter "myViewModel.ts" 在文件名文本框中,输入“myViewModel.ts”
  • Click button "Add" 点击“添加”按钮

Modify file myViewModel.ts... 修改文件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 添加RequireJS配置文件

  • Right-click project folder "Application" in the Solution Explorer 在解决方案资源管理器中右键单击项目文件夹“Application”
  • select context menu item "Add"->"New Item..." 选择上下文菜单项“添加” - >“新项目...”
  • In left-hand pane, highlight "Visual C#" 在左侧窗格中,突出显示“Visual C#”
  • In right-hand pane, highlight "TypeScript File" 在右侧窗格中,突出显示“TypeScript文件”
  • In file name text box, enter "require-config.ts" 在文件名文本框中,输入“require-config.ts”
  • Click button "Add" 点击“添加”按钮

Modify file "require-config.ts" 修改文件“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 修改现有文件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. 完成,在.ts文件中设置一些断点,然后点击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. 如果运行该示例,并单击该按钮,您会发现index.html上的按钮绑定到myViewModel.ts中名为myButton_Click的方法。 Also, the text box myStringTest2, and myNumberTest are bound to variables defined in the view model. 此外,文本框myStringTest2和myNumberTest绑定到视图模型中定义的变量。

The require-config.ts file holds the list of dependencies that are wired up. require-config.ts文件包含已连接的依赖项列表。 The line "knockout.applyBindings(viewModel)" associates the instance of myViewModel with the html view. “knockout.applyBindings(viewModel)”行将myViewModel的实例与html视图相关联。

Notice how TypeScript allows variables to be declared with a data type? 请注意TypeScript如何允许使用数据类型声明变量?

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. KnockoutJS有一些很酷的插件 - 比如knockout-mapping - 它允许从Web服务中提取的数据直接绑定到视图模型而不需要中间转换或转换。 Also, knockoutjs can support templating - presumably so master pages can be implemented. 此外,knockoutjs可以支持模板化 - 大概可以实现母版页。

For completeness, I will add a project folder called Views, and hold my html there. 为了完整起见,我将添加一个名为Views的项目文件夹,并在那里保存我的html。 I think that is more traditional for MVC/MVVM development. 我认为这对于MVC / MVVM开发来说更为传统。 The url having .html is still nagging me. 有.html的网址仍在唠叨我。 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. 我喜欢MVC风格的路由(没有文件扩展名),但这也很酷 - 特别是因为它只不过是HTML和JavaScript - 真正的跨平台。 Aside from web services calls (not included in the example) there are no postbacks, client side processing is fast. 除了Web服务调用(不包括在示例中),没有回发,客户端处理速度很快。

Please feel free to comment... 请随意发表评论...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM