Use JavaScript to build your first Metro application (on Windows 8) (1)

Source: Internet
Author: User
Document directory
  • Target

Web technologies, including HTML, CSS, and javsscript, are being adopted by Metro-style programs as the first class development technology in Windows programs. In comparison, JavaScript is not deployed on one page after another as a traditional Web server, and Metro app is locally installed on the client machine. This is similar to the traditional win program, but it can directly use JavaScript to access the underlying API and communicate with other programs.

Note: If you prefer C #, C ++, or vB withxaml for development, see buildingyour first Windows Metro style app with C #, C ++, or VB.

 

Target

In this tutorial, we will show you how to build a metro-style program using javascrip. Using HTML5, stacked Style Sheets (css3), and JavaScript technologies, we will work with you to create a lightweight RSS client, and try to make the program better personalized (that conveys the right personality ). We will introduce core contents including controls, functions, layout, templates, data binding, and JS libraries. The technologies mentioned have been optimized in Metro app development, easy to use. Based on this tutorial, you should have the ability to initially develop the JS version of Metro app after learning. The tutorial is divided into three small sections. It is estimated that you will finish reading the section in 20 minutes. Of course, if you do a good job in each exercise, it may take a little longer.

Hello win Metro

As with Web pages, you must first have an HTML file to write the metro app.

 

[HTML]View plaincopyprint?
  1. <! Doctype HTML>
  2. <HTML>
  3. <Head> <title> hello, Windows Metro styleapps! </Title>
  4. <Body>
  5. </Html>


 

If you put this HTML in a browser to run it, it will be meaningless. Needless to say, if it is executed in the Metro app, it is another world. Of course, your customers generally do not care whether it is a browser or a Metro app. The difference is that the metro app will be installed in the window store, just like other win programs. Furthermore, a single web page is not a complete program, even those involving style, code, and image resources. Now, the metro app not only includes these but also provides standard applications, so there will be metadata and program resource files:

  • The manifest file used to describe the program itself, including the program name, introduction, and launch page.

  • The image or icon file used for appearance.

  • The icon logo used for Windows Store display.

  • A splash screen is used when your program starts ).

Manifest is an XML file named appxmanifest. xml. This file contains details such as program name, program description, and image reference. One of the most important information is the startup page of the specified program. Microsoft Visual Studio 11 express for Windows Developer Preview can automatically export the program list and help you complete a series of tasks through JavaScript, these tasks are used to create, edit, package, start, and debug your Metro-style applications.

Develop windows Metro Apps in

Microsoft Visual Studio is the tool for developing Windows programs and the first tool for developing Metro programs. It not only provides HTML, CSS, JavaScript, image editing, and general development tasks such as editing program lists using JavaScript, but also includes project management throughout the development cycle, it involves many processes such as source code management, integrated build, and deployment. There are several vs versions. Here we use the free Visual Studio 11 express for Windows Developer Preview preview version, which is available in Windows software development kit (SDK) for metroapp. After the installation, the compilation, packaging, and deployment tools are installed. Visualstudio 11 express for Windows Developer Preview provides several templates, as shown in:

 

The simplest project template is blank application. After running the program, a file exclusive to the Visual Studio 11 express for windowsdeveloper preview Metro style app using JavaScript project (. wwaproj) is generated ).

 

Now, if you open the default default.html file, you will find that it is almost all empty content. The same applies to open the default. js file under the JS directory. Obviously, the main file is provided here, waiting for you to create something to add.

For debugging, you can click "Debug> startdebugging". It provides several debugging tools that developers are familiar:

  • Debuggers, breakpoint, step-by-step, and monitoring JS data and behavior.

  • JS Console window (JavaScript consolewindow), where the JavaScript Object command line interacts.

  • Dom browser window, observe the HTML Document Object Model or element style.

  • Simulator: simulates events of related devices in the development environment.

Metroapp written in Javascript, except for its syntax, is similar to other languages when accessing the underlying Windows platform. However, according to some features of JavaScript programmers, there should be some predefined packages that can be used repeatedly. That is to say, the Windows Class Library provides a set of reusable JS and CSS files for Javascript, so as to better reflect the new features of windows. The vs template contains a series of CSS style rule tables to provide a uniform look & feel ). The simplest way is to introduce it through the project template file, which automatically contains the files required by winjs.

Although the blank application project file is empty, it already contains certain styles. The reason why the metro style is called "style" is that there are some requirements on the style. Style itself does not mean uniformity, because in many cases you need a specific layout, personalized design. Here is an example. In fact, although the so-called Metro-style programs are new things, past experiences are still worth studying. Here we will introduce Raymond Chen, a well-developed developer in the window project team. Mr. Chen is the author of the old new thing, and also the author of weblog.

Mr Chen's main achievement is that the average person is not easy to see the lack of the win platform, or the lack of the United States, and the text and sample resources are actively posted on his blog. In this way, all are win programs. We can use these materials to demonstrate new constructor methods.

Therefore, we need to download data from his blog to find out where to place the code.

Call the winjs. Application Object

The default.html file generated by the project template loads JS and CSS files with the lowest requirements required by winjs by default:

 

[HTML]View plaincopyprint?
  1. <! Doctype HTML>
  2. <HTML>
  3. <Head>
  4. <Meta charset = "UTF-8"/>
  5. <Title> rssreader </title>
  6. <! -- Winjs references -->
  7. <LINK rel = "stylesheet" href = "/winjs/CSS/ui-dark.css"/>
  8. <SCRIPT src = "/winjs/JS/base. js"> </SCRIPT>
  9. <SCRIPT src = "/winjs/JS/wwaapp. js"> </SCRIPT>
  10. <! -- Rssreader references -->
  11. <LINK rel = "stylesheet" href = "/CSS/default.css"/>
  12. <SCRIPT src = "/JS/Default. js"> </SCRIPT>
  13. </Head>
  14. <Body>
  15. </Body>
  16. </Html>

Add our own content:

 

 

[HTML]View plaincopyprint?
  1. <Body>
  2. <H1> the old New thing
  3. <Div id = "downloadstatus"> </div>
  4. <Div id = "posts"> </div>
  5. </Body>

 

The above is a title and two DIV elements used for the role of the container (placeholder), one indicating the status of the RSS download; the other for us to get the future display of RSS content. Don't forget, we will use those style files of Brother Chen:

 

[CSS]View plaincopyprint?
  1. /* Default.css */
  2. Body
  3. {
  4. Background-color: # FFF;
  5. Color: #000;
  6. Font-family: verdana;
  7. Padding: 8pt;
  8. }
  9. A: Link, A: visited, A: active
  10. {
  11. Color: #700;
  12. Font-weight: Inherit;
  13. }
  14. H1
  15. {
  16. Text-transform: none;
  17. Font-family: Inherit;
  18. Font-size: 22pt;
  19. }
  20. # Posts
  21. {
  22. Width: 99%;
  23. Height: 100%;
  24. Overflow: auto;
  25. }
  26. . Posttitle
  27. {
  28. Color: #700;
  29. Font-size: 1.2em;
  30. Font-weight: bold;
  31. }
  32. . Postdate
  33. {
  34. Color: #666;
  35. Font-size: 11pt;
  36. }
  37. . Postcontent
  38. {
  39. Font-size: medium;
  40. Line-Height: 18px;
  41. }

To integrate metroapp with other applications, Windows provides a set of application-level message events, which are fully encapsulated by winjs. The default. js file subscribes to (or registers) the loading event of the program. When the program is enabled, it will execute:

 

[JavaScript]View plaincopyprint?
  1. // Default. js
  2. (Function (){
  3. 'Use strict ';
  4. // Uncomment the following line to enable first chanceexceptions.
  5. // Debug. enablefirstchanceexception (true );
  6. Winjs. application. onmainwindowactivated = function (e ){
  7. If (E. Detail. Kind === windows. ApplicationModel. Activation. activationkind. Launch ){
  8. // Todo: Write the startup code here.
  9. }
  10. }
  11. Winjs. application. Start ();
  12. })();

First, you must pay attention to the fact that the above Code runs in an automatically executed anonymous function. This is a javascript practice that avoids global space pollution and is often recommended. Second, please note DebugThe enableFirstChanceExceptionMethod. If you cancel the annotation, it will report the initial JavaScript exception to the vs debugger, which is very convenient to say.

 

After the preliminary work is completed, the code will be loaded in the program and its resources (such as default.html) to trigger the event after the objects are obtained from winjs. This is an excellent place and time for execution initialization. We will see it later. To trigger any program event, you must let the program know that you are ready to introduce the message, that is, how to execute the message. Onmainwindowactivated event handler is an excellent place for us to download Mr. Chen's blog.

Use winjs. xhr to download data

The xhr function in the winjs namespace provides a series of Optional options for downloading data from the HTTP protocol, both common text and XML. Xhr indicates XMLHttpRequest. Xhr in winjs is a package that can be sent to many parameters, including HTTP verb (default get), HTTP header (default none), and source URL for getting data.

 

[JavaScript]View plaincopyprint?
  1. Winjs. application. onmainwindowactivated = function (e ){
  2. If (E. Detail. Kind === windows. ApplicationModel. Activation. activationkind. Launch ){
  3. // Start download
  4. Downloadstatus. innertext = "downloading posts ...";
  5. Winjs. xhr ({URL: "http://blogs.msdn.com/ B /oldnewthing/rss.aspx "}).
  6. Then (processposts, downloaderror );
  7. }
  8. }


 

Different from XMLHttpRequest objects, you can select synchronously or asynchronously for different communication methods. xhr () can only be used for asynchronous communication. Its consideration is to prevent UI blocking caused by synchronous communication. The encoding model in asynchronous mode helps you write more responsive applications. In this example, we do not know how long the request takes. Therefore, we arrange a div to serve as the UI container for feedback on downloadstatus.

Asynchronous functions under the winjs object are called "Promise promise", indicating future results. The promise object exposes the then function, namely the success function, failure function, and prgress function. Call xhr () to immediately return the promise object, so we set the specific situation of the three functions.

 

[JavaScript]View plaincopyprint?
  1. Function processposts (request ){
  2. // Clear the prompt content
  3. Downloadstatus. innertext = "";
  4. // Parse RSS
  5. VaR items = request. responsexml. selectnodes ("// item ");
  6. If (items. Length = 0) {downloadstatus. innertext = "An error occurred while downloading the post. ";}
  7. For (VAR I = 0, Len = items. length; I <Len; I ++ ){
  8. VaR item = items [I];
  9. // Add data to # posts Div
  10. VaR parent = Document. createelement ("Div ");
  11. Appenddiv (parent, item. selectnodes ("title") [0]. Text, "posttitle ");
  12. Appenddiv (parent, item. selectnodes ("pubdate") [0]. Text, "postdate ");
  13. Appenddiv (parent, item. selectnodes ("Description") [0]. Text, "postcontent ");
  14. Posts. appendchild (parent );
  15. }
  16. }
  17. Function appenddiv (parent, HTML, classname ){
  18. VaR DIV = Document. createelement ("Div ");
  19. Div. innerhtml = HTML;
  20. Div. classname = classname;
  21. Parent. appendchild (DIV );
  22. }
  23. Function downloaderror (){
  24. Downloadstatus. innertext = "An error occurred while downloadstatus. innertext =. ";
  25. }

When the HTTP request is called, we then execute the processposts function. The parameter request object (a request object) is like XMLHttpRequest, which is like the responsexml attribute we care about, this is the result we requested, that is, RSS data. RSS itself is also a standard XML document, so we can use XPath expressions to select nodes in rssfeed, extract the title, pubdta, and content of each item, and finally render it into the DIV element. For readers of the past "theold new thing", the output of the program may be similar.

 

Someone may ask if the xhr function will work because the web server's production page may fail. The reason for working is that the Javascript Metro program runs in a local and secure context, and can only use the requests and user-defined functions listed by the program.

Next

You already know how to use js to write a Metro app, but the APIS you come into use are only a small part of the win class library. What we will announce next is "extended your first Windows Metro style app extending your first Windows Metro style app", to discover the secrets of Windows runtime and controls with you!

 

Original article address

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.