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. directly using JavaScript, you can access the underlying layer 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.
View plaincopy to clipboardprint? <! DOCTYPE html>
<Html>
<Head> <title> hello, Windows Metro styleapps! </Title> <Body> </Html>
<! DOCTYPE html>
<Html>
<Head> <title> hello, Windows Metro styleapps! </Title> <Body> </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 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 also The author of The Old New Thing, and he also has 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:
View plaincopy to clipboardprint? <! DOCTYPE html>
<Html>
<Head>
<Meta charset = "UTF-8"/>
<Title> RssReader </title>
<! -- WinJS references -->
<Link rel = "stylesheet" href = "/winjs/css/ui-dark.css"/>
<Script src = "/winjs/js/base. js"> </script>
<Script src = "/winjs/js/wwaapp. js"> </script>
<! -- RssReader references -->
<Link rel = "stylesheet" href = "/css/default.css"/>
<Script src = "/js/default. js"> </script>
</Head>
<Body>
</Body>
</Html>
<! DOCTYPE html>
<Html>
<Head>
<Meta charset = "UTF-8"/>
<Title> RssReader </title>
<! -- WinJS references -->
<Link rel = "stylesheet" href = "/winjs/css/ui-dark.css"/>
<Script src = "/winjs/js/base. js"> </script>
<Script src = "/winjs/js/wwaapp. js"> </script>
<! -- RssReader references -->
<Link rel = "stylesheet" href = "/css/default.css"/>
<Script src = "/js/default. js"> </script>
</Head>
<Body>
</Body>
</Html> add our own content:
View plaincopy to clipboardprint? <Body>
<H1> The Old New Thing <Div id = "downloadStatus"> </div>
<Div id = "posts"> </div>
</Body>
<Body>
<H1> The Old New Thing <Div id = "downloadStatus"> </div>
<Div id = "posts"> </div>
</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:
View plaincopy to clipboardprint? /* Default.css */
Body
{
Background-color: # fff;
Color: #000;
Font-family: Verdana;
Padding: 8pt;
}
A: link, a: visited, a: active
{
Color: #700;
Font-weight: inherit;
}
H1
{
Text-transform: none;
Font-family: inherit;
Font-size: 22pt;
}
# Posts
{
Width: 99%;
Height: 100%;
Overflow: auto;
}
. PostTitle
{
Color: #700;
Font-size: 1.2em;
Font-weight: bold;
}
. PostDate
{
Color: #666;
Font-size: 11pt;
}
. PostContent
{
Font-size: medium;
Line-height: 18px;
}
/* Default.css */
Body
{
Background-color: # fff;
Color: #000;
Font-family: Verdana;
Padding: 8pt;
}
A: link, a: visited, a: active
{
Color: #700;
Font-weight: inherit;
}
H1
{
Text-transform: none;
Font-family: inherit;
Font-size: 22pt;
}
# Posts
{
Width: 99%;
Height: 100%;
Overflow: auto;
}
. PostTitle
{
Color: #700;
Font-size: 1.2em;
Font-weight: bold;
}
. PostDate
{
Color: #666;
Font-size: 11pt;
}
. PostContent
{
Font-size: medium;
Line-height: 18px;
} 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:
View plaincopy to clipboardprint? // Default. js
(Function (){
'Use strict ';
// Uncomment the following line to enable first chanceexceptions.
// Debug. enableFirstChanceException (true );
WinJS. Application. onmainwindowactivated = function (e ){
If (e. detail. kind === Windows. ApplicationModel. Activation. ActivationKind. launch ){
// TODO: Write the startup code here.
}
}
WinJS. Application. start ();
})();
// Default. js
(Function (){
'Use strict ';
// Uncomment the following line to enable first chanceexceptions.
// Debug. enableFirstChanceException (true );
WinJS. Application. onmainwindowactivated = function (e ){
If (e. detail. kind === Windows. ApplicationModel. Activation. ActivationKind. launch ){
// TODO: Write the startup code here.
}
}
WinJS. Application. start ();
}) (); First, you must note 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, pay attention to the enableFirstChanceException method called in the Debug namespace. 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.
View plaincopy to clipboardprint? WinJS. Application. onmainwindowactivated = function (e ){
If (e. detail. kind === Windows. ApplicationModel. Activation. ActivationKind. launch ){
// Start download
DownloadStatus. innerText = "downloading posts ...";
WinJS. xhr ({url: "http://blogs.msdn.com/ B /oldnewthing/rss.aspx "}).
Then (processPosts, downloadError );
}
}
WinJS. Application. onmainwindowactivated = function (e ){
If (e. detail. kind === Windows. ApplicationModel. Activation. ActivationKind. launch ){
// Start download
DownloadStatus. innerText = "downloading posts ...";
WinJS. xhr ({url: "http://blogs.msdn.com/ B /oldnewthing/rss.aspx "}).
Then (processPosts, downloadError );
}
}
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", 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.
View plaincopy to clipboardprint? Function processPosts (request ){
// Clear the prompt content
DownloadStatus. innerText = "";
// Parse RSS
Var items = request. responseXML. selectNodes ("// item ");
If (items. length = 0) {downloadStatus. innerText = "An error occurred while downloading the post. ";}
For (var I = 0, len = items. length; I <len; I ++ ){
Var item = items [I];
// Add data to # posts div
Var parent = document. createElement ("div ");
AppendDiv (parent, item. selectNodes ("title") [0]. text, "postTitle ");
AppendDiv (parent, item. selectNodes ("pubDate") [0]. text, "postDate ");
AppendDiv (parent, item. selectNodes ("description") [0]. text, "postContent ");
Posts. appendChild (parent );
}
}
Function appendDiv (parent, html, className ){
Var div = document. createElement ("div ");
Div. innerHTML = html;
Div. className = className;
Parent. appendChild (div );
}
Function downloadError (){
DownloadStatus. innerText = "An error occurred while downloadStatus. innerText =. ";
}
Function processPosts (request ){
// Clear the prompt content
DownloadStatus. innerText = "";
// Parse RSS
Var items = request. responseXML. selectNodes ("// item ");
If (items. length = 0) {downloadStatus. innerText = "An error occurred while downloading the post. ";}
For (var I = 0, len = items. length; I <len; I ++ ){
Var item = items [I];
// Add data to # posts div
Var parent = document. createElement ("div ");
AppendDiv (parent, item. selectNodes ("title") [0]. text, "postTitle ");
AppendDiv (parent, item. selectNodes ("pubDate") [0]. text, "postDate ");
AppendDiv (parent, item. selectNodes ("description") [0]. text, "postContent ");
Posts. appendChild (parent );
}
}
Function appendDiv (parent, html, className ){
Var div = document. createElement ("div ");
Div. innerHTML = html;
Div. className = className;
Parent. appendChild (div );
}
Function downloadError (){
DownloadStatus. innerText = "An error occurred while downloadStatus. innerText =. ";
} 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 are concerned 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. Next we will announce Extendingyour first Windows Metro style app, which will help you discover the secrets of Windows Runtime and controls!
Author: "zhangxin's column"