Use C # To write Javascript

Source: Internet
Author: User
Tags mscorlib

The maintenance of JavaScript code in front-end development is always a headache, especially in rich client applications, it is necessary to write a very large JavaScript code, although JavaScript claims to be an object-oriented language, however, the support for inheritance and strong types in Modern Languages is very limited. If we can apply the features in the C # language to Javascript, it will certainly greatly improve the maintainability of JavaScript code and the development efficiency. The saltarelle compiler is such a tool that can compile C # code into JavaScript code.

This article will show you how to use saltarelle to write JavaScript code. We will explain how to use saltarelle with the saltarelle. jquery and saltarelle. Knockout libraries. This document uses Visual Studio 2012 as a development tool and uses nuget to obtain related extension packages.

1. Create an empty ASP. NET application project as a front-end demonstration website. The project name is Web

2. Add a class library project as a Javascript script project. This project uses the saltarelle compiler to automatically generate script code. The project name is scripts.

3. Select the scripts project, right-click, and choose manage nuget packages. On the package management page, enter saltarelle in the search window at the top to search for packages related to saltarelle:

Install saltarelle C # To JavaScript compiler, Runtime Library for the saltarelle C # To JavaScript... Metadata required to use jquery with saltarelle... Metadata required to use knockout with saltarelle...

4. The saltarelle package updates the scripts project, adds Necessary assembly references, and modifies the project to use the saltarelle compiler. Due to the bug in Visual Studio, We need to manually uninstall and re-load the scripts project. This operation is completed by right-clicking the project menu.

5. Modify the scripts project type: Right-click the scripts project, select properties, and select "console application" from the output type ", the reason for this modification is that the saltarelle compiler automatically calls the scripts entry method (that is, the main method of program)

6. Open the assemblyinfo. CS code file in the properties folder and comment out the comvisible and guid features:

// Set comvisible to false to make the type in this Assembly invisible to the COM component. If you need to access the types in this Assembly from com, // set the comvisible attribute on this type to true. //[Assembly: comvisible (false)]// If this project is made public to com, the following GUID is used for the ID of the Type Library //[Assembly: GUID ("ecc66b86-53da-44b6-b83a-87b52da11e91")]

7. Modify the class1.cs code file automatically added to the scripts project to program and add the main method:

namespace Scripts{    class Program    {        static void Main()        {        }    }}

8. Generate a scripts project. After the scripts. js file is generated, you can view the generated scripts. js file in the generated output directory.

Next, we will demonstrate how to use jquery:

In jquery, you can use ready to register the program to be executed after the page is loaded. in jquery, we can use the ondocumentready method to complete the same functions. The following example shows how to enable the prompt box function after page loading is complete:

1. Add the system. html and jqueryapi namespaces to program. CS.

2. Modify the main method. The Code is as follows:

using System.Html;using jQueryApi;namespace Scripts{    class Program    {        static void Main()        {            jQuery.OnDocumentReady(() =>            {                Window.Alert("Page is loaded");            });        }    }}

Next, how do we use the generated JS file in a web project? In fact, the JS Code generated using scripts is exactly the same as other JS Code, but before referencing the compiled JS file, we need to reference the JS at saltarelle runtime. This JS can be found in the salarelle. runtime package directory:

1. Create a directory named scripts in the web project to save the JS files in the project.

2. Open the solution folder and copy mscorlib. js or mscorlib. Min. js (compressed version) under packages \ saltarelle. runtime.2.2.0 to the scripts directory of the web project.

3. Of course, because jquery is used, you must copy the jquery library file to the scripts directory. The jquery JS file also exists in the packages \ saltarelle. jquery.1.9.0 directory.

4. To ensure the scripts under scripts. JS is always the latest. We can copy the command in the event after the scripts project is generated to replace scripts. copy js to the scripts directory of the web project: In the scripts project properties, select generate event and enter the following command in the generated event:

Copy $ (targetdir) $ (targetname). js $ (solutiondir) web \ scripts \ $ (targetname). js

5. To ensure that the scripts. js script is automatically updated when a web project is generated, you can add a reference to the scripts project in the web project.

6. Create an HTML page named index.html in the webproject. Add references to necessary JS files in the head Tag:

<!DOCTYPE html>

7. Start debugging. After the page is opened, the "page is loaded" prompt will pop up.

Knockout is a library that implements mvvm mode in JS. It can provide functions similar to Data Binding in WPF.

1. First, add a viewmodel class to the scripts project. The Code is as follows:

Using system; using knockoutapi; namespace scripts {public class indexviewmodel {// page title. Use observable to indicate that this field supports change notification. When the value changes, the associated UI automatically updates public observable <string> pagetitle = knockout. observable <string> (); // indicates the array public observablearray <logitem> logs = knockout. observablearray <logitem> ();} public class logitem {Public String level = string. empty; Public datetime time; Public String message = string. empty ;}}

Note: For how to use knockout to implement mvvm mode, refer to the official website of knockout.

2. Bind viewmodel to the main method:

Using system. HTML; using jqueryapi; using knockoutapi; namespace scripts {class program {static void main () {jquery. ondocumentready () => {window. alert ("page is loaded"); indexviewmodel Vm = new indexviewmodel (); VM. pagetitle. value = "not named"; knockout. applybindings (VM );});}}}

3. Copy the knockout library file in the package to the scripts directory of the web project.

4、add a reference to the JS file of the knockout library in the index.html File

<script type="text/javascript" src="Scripts/mscorlib.min.js"></script>    <script type="text/javascript" src="Scripts/jquery-1.9.1.js"></script>    <script type="text/javascript" src="Scripts/knockout-2.2.0.min.js"></script>    <script type="text/javascript" src="Scripts/Scripts.js"></script>

5. Use viewmodel in index.html to bind data

<! Doctype HTML> <HTML xmlns = "http://www.w3.org/1999/xhtml"> 

Note that when the salarelle compiler generates a JS file, it automatically converts the name in C # To the JS specification. Therefore, we can see that in HTML, the fields used for data binding start with lowercase letters.

6. There is a "modify Title" button in HTML. We need to add an event handler function for this button. Here we use jquery's Click Event binding method, add the following code to the main method and ondocumentready:

Jquery. select ("# btnedit "). click (S) => {VM. pagetitle. value = "title" + datetime. now. tostring ("yyyy-mm-dd hh: mm: SS"); VM. logs. value = VM. logs. value. concat (New logitem () {level = "information", time = datetime. now, message = "modified title "});});

The code is simple. Modify pagetitle directly and add a log to the log list.

7. Start debugging and click the button on the page to perform the debugging.

 

Source code download

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.