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

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

问题描述

我一直在寻找一个简单的操作方法,使用RequireJS,jQuery和KnockoutJS创建Visual Studio 2012 TypeScript项目的最基本示例。有几个可用的例子,但对我来说,有些比我想要的更复杂,所以我开始创建一个方法,并将其发布在这里供公众审查。我已经回答了我自己的问题,作为Q& A风格的知识共享练习。

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

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 - 用于HTML文档遍历和操作,事件处理,动画和Ajax交互的JavaScript框架。

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

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

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 - 利用MVVM模式进行UI绑定。 HTML视图引用视图模型中的变量和方法。视图模型是一个JavaScript对象(JavaScript文件可能是编译.ts文件的结果 - 请参阅上面的TypeScript)。

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 - 还包括两个DefinitelyTyped NuGet包。由于TypeScript正在尝试验证数据类型的使用情况,因此它正在执行检查以确保它知道所有引用。 JavaScript比这更松散。为了满足TypeScript(当引用外部JavaScript对象时),我们需要一种方法来描述(对TypeScript)我们期望使用的对象。这些DefinitelyTyped脚本提供了此定义。它们不提供任何功能,只是TypeScript编译器的清晰度,因此它可以执行这些检查。

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" />

这是TypeScript编译器将包含requirejs DefinitelyTyped定义文件的方式。创建这些DefinitelyTyped脚本的组织创建了一个庞大的集合。这里我们只提到两个 - KnockoutJS和RequireJS(好吧,因为这是本教程的范围)

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)

推荐答案

免责声明



这个操作方法将显示使用TypeScript,jQuery,KnockoutJS构建基本网站的 a 方式,和RequireJS。还有很多其他方法可以做到。

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.

安装Visual Studio Extension

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

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项目


  • 启动visual studio 2012。

  • 选择菜单项文件 - > - >项目 ...

  • 导航到模板 - >其他语言 - > TypeScript (这个
    实际上创建了一个扩展名为.csproj的项目文件 - 很奇怪)

  • 选择项目类型使用TypeScript的HTML应用程序

  • 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"

删除文件应用。来自项目的css,app.ts

Remove file app.css, app.ts from project

使用NuGet,添加...

Using NuGet, add...


  • RequireJS (我为本教程选择了2.1.15版本) )

  • KnockoutJS (我为本教程选择了3.2.0版本)

  • jQuery (我为本教程选择了2.1.1版)

  • requirejs.TypeScript.DefinitelyTyped (我为本教程选择了版本0.2.0 by
    Jason Jarrett。它安装了一个打字稿def文件
    作者Josh Baldwin - 版本2.1.8)

  • knockout.TypeScript.DefinitelyTyped (我选择版本0.5.7由
    Jason Jarrett为本教程)

  • 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)

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

Create project folders at root of project


  • 申请

  • 模特

  • ViewModels

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

Add TypeScript file to project folder "Models"


  • 右键单击Solution Explorer中的Models文件夹

  • 选择上下文菜单项Add - >New Item ...

  • 在左侧窗格中,突出显示Visual C#

  • 在右侧窗格中,突出显示TypeScript文件

  • 在文件名文本框中,输入myTestModel.ts单击按钮添加

  • 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"

修改文件myTestModel.ts

Modify file "myTestModel.ts"

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






创建TypeScript视图模型



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


Create a TypeScript view-model

Add TypeScript file to project folder "ViewModels"


  • 右键单击文件夹ViewModels在解决方案资源管理器中

  • 选择上下文菜单项添加 - >新项目...

  • 在左侧窗格中,突出显示 Visual C#

  • 在右侧窗格中,突出显示TypeScript文件

  • 在文件名文本框中输入myViewModel.ts

  • 点击按钮添加

  • 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"

修改文件myViewModel.ts ...

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;






添加配置



添加RequireJS配置文件


Add configuration

Add RequireJS configuration file


  • 在解决方案资源管理器中右键单击项目文件夹Application

  • 选择上下文菜单项添加 - >新项目...

  • 在左侧窗格中,突出显示Visual C#

  • 在右侧窗格中,突出显示TypeScript文件

  • 在文件名文本框中,输入require-config.ts

  • 点击按钮添加

  • 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"

修改文件require-config.ts

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);
        });
    });
});






修改现有文件index.html



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


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>






运行



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


Run it

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

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

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.

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

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.

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

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

我希望这篇入门书有所帮助。只是将几件放在桌子上帮助我想象出这些组件如何一起玩。 KnockoutJS有一些很酷的插件 - 比如knockout-mapping - 它允许从Web服务中提取的数据直接绑定到视图模型而不需要中间转换或转换。此外,knockoutjs可以支持模板 - 大概可以实现母版页。

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.

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

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天全站免登陆