天天看點

運用JavaScript建構你的第一個Metro式應用程式(onWindows 8)(二)

先前的學習中,我們已經了解了 Metro式的 JavaScript 應用程式大緻如何,以及通過使用 Microsoft Visual Studio 11 Express for Windows Developer Preview 搭建你的應用程式。接下來要探讨的是,把  Windows 平台的所提供的功能,呈現在您眼前,為擴充您的程式而準備!

<dl><dt>In the previous topic, you learned about Metro style app usingJavaScript, and used Microsoft Visual Studio 11 Express for WindowsDeveloper Preview to create a framework for your first app. Now it'stime to extend your application using functionality</dt></dl>

exposed by theWindows platform.

<dl></dl>

<dt>This topic is the second in a series describing how to build yourfirst Windows Metro style app using JavaScriptMetro style app usingJavaScript. If you haven't already done so, read Building your firstWindows Metro style app before you read this topic. Familiarity</dt>

withHTML5, Cascading Style Sheets, Level 3 (CSS3), and JavaScript ishelpful, but not essential, to understanding this topic.

<dt>當使用者從 Windows Store 處安裝程式的時候,Windows 會對應用程式的中繼資料作分析,認定那些依賴條件(Capabilities)。例如,要求通路網際網路、通路文檔、圖檔、播放音頻視訊的時候,又或者通路如攝像頭、麥克風等的硬體時候,必須先告知使用者,我這個程式需要些以上何種何種的條件才能運作。要使用者首肯才能使用這些資源或裝置。反之,如果沒有列出的那些資源或裝置,則一定不是依賴的條件,而且一定不能夠運作的(譯注:意思即是未列出的就不運作)。程式所需要的依賴條件列明在程式清單(manifest)中,具體說,就是你可以輕按兩下“Visual </dt>

Studio Solution Explorer ”裡面的 package.appxmanifest 檔案,點選 “Capabilities” 标簽頁就可以選擇你需要的依賴條件。預設下,你的項目都是設定有最常見的依賴條件,具備充當 Internet 用戶端的條件。

<dt>When a user installs an app from the Windows Store, Windows use theapp's metadata to figure out what capabilities it needs to run. Forexample, accessing data from the internet, accessing documents,pictures, music or videos or getting access to hardware</dt>

like themicrophone or webcam. At install time, the user sees whichcapabilities an app asks for, so the app is installed only if theuser agrees for it to access those resources. If the app hasn'tlisted itself as needing access to a certain kind of resource,

itisn't allowed access at run time. An app lists the capabilities itneeds in the manifest, so you can double-click on thepackage.appxmanifest file in the Visual Studio Solution Explorer,click the Capabilities tab and select the ones you need. By default,your

project has the most common capability enabled, the ability toact as a client for internet service.

目前為止,程式運作起來,仍屬于浏覽器技術的一部分内容,至今還未真正接觸到 Windows 平台的運作時,特定稱謂 “WindowsRuntime”,簡稱 “WinRT”。而 WinJS,就是允許在 JavaScript Metro 式的應用程式中,借此對象可以通路到 Windows Runtime 類庫裡面許許多多的功能。通過這個命名空間你還可以通過 Metr app 文檔區翻閱更詳盡功能。比如現在我們所使用的 Windows.Web.Syndication,用它直接擷取已解析的 RSSReed,好處是不用在處理

RSS 或 ATOM 的之間上考慮怎麼用 Xpath 的問題而浪費時間。

So far, we haven't really used the Windows platform on which ourapp is running, instead we used the web technologies that are alsopart of the browser. But in addition to WinJS, a Metro style appusing JavaScript can access a large amount of functionality

in theWindows Runtime, broken up into namespaces that you can explore inthe Metro style app reference section. The namespace we want isWindows.Web.Syndication, because it has the SyndicationClient classthat we can use to retrieve a fully-parsed RSS feed. This

saves usthe trouble of XPath or worrying about the difference between RSS andATOM.

無須太多語句或者項目引用,Metro App 下的 WinRT 元素就直接可用,這樣使用 SyndicationClient 非常地簡單。

The elements of the WinRT are available to Metro style apps usingJavaScript without any additional script includes or projectreferences, so using the SyndicationClient is simple:

建立 SyndicationClient 對象之後接着建立一個 URL對象,并将其送入 RetrieveFeedAsync 進行下載下傳。就像其他數量龐大的 Windows Runtime 函數那樣,RetrieveFeedAsync 是異步的,自然也會産生“允諾Promise”。這樣處理 RSS 的話更簡單一些了:

After creating the SyndicationClient object, we create a URLobject and feed it to the RetrieveFeedAsync method to start thedownload. Like a large number of Windows Runtime functions,RetrieveFeedAsync is asynchronous and therefore produces a promise.Processing

the RSS becomes a little bit easier now:

回想一下,調用 xhr 的情況是提供 XML 然而并沒有為我們解析XML 為對象,不同于 xhr 現在 SyndicationClient卻包辦搞定了,省卻了循環的代碼。結果雖然是一樣,但其實後者會好一點。接下來介紹的資料綁定會幹得更漂亮的說。

Unlike in the case of the xhr call, which provided XML but didn'tparse the RSS into objects for us, SyndicationClient does just that,simplifying our iteration code. The result looks the same, but thecode is a little nicer. And we can do even better by using

templatesand data binding.

看看 processPosts 函數與 appendDiv 函數結合的地方,你會發現那些靜态的内容都被變量替換掉了。這種模式就是我們常說的模闆(Template)。WinJS 考慮到這一功能,其文法如下所示:

If you look at the combination of the processPosts and appendDivfunction, you notice that we're mixing static content with variablesubstitution in code. This pattern of UI creation is known as atemplate. WinJS come with a similar feature and the syntax looks

likethis:

WinJS.Binding.Template 的 JavaScript 構造器(constructor),該構造器擷取了 div 以便為 div 登記相關的事件。順便說一下,這也是在 WinJS 中聲明一個控件的基礎步驟。要觸發 data-win-control 屬性及其事件的執行,必須通過呼叫 WinJS.UI.processAll()。應該在哪個地方調用這個方法呢?事件 onmainwindowactivated 那裡便最适合不過了。

To use WinJS templates, we must reference the bulk of the WinJSCSS and JavaScript files. These files provide the styles and behaviorfor the data-win-control attribute, among other things. HTML5 definesthe set of data-* attributes that we use for anything

app-specific wewant to associate with an HTML element. In this case, we declare aJavaScript constructor function name WinJS.Binding.Template. Thisconstructor gets the associated div so that it can attach itself andprovide the necessary behavior. This is the

foundation fordeclarative controls in WinJS. To cause the data-win-controlattributes to be executed, you must call WinJS.UI.processAll, whichis an excellent addition to your onmainwindowactivated event handler:

調用 processAll 則就是執行 WinJS.Binding.Template 的構造器函數,構造器内部具體的過程便是查找擁有屬性 data-win-bind 的那些 div,代碼如下:

The call to processAll causes the WinJS.Binding.Templateconstructor to be called, which in turn parses the contents of thediv looking for data-win-bind attributes in the following format:

如何構成資料綁定?請注意分号前面的部分為元素屬性值(attribute)與分号後面的部分為 JavaScript 屬性名稱(property)。不管何種對象,模闆隻要遇到與屬性(property)相吻合的情形即會渲染出來。于是,兩者形成了綁定的關系,資料轉化為特定的内容。是以模闆這裡的地方,我們的  processPosts 函數改為:

The attribute establishes a data binding relationship between theelement attribute name before the colon (innerText or innerHTML inour sample) and the JavaScript property name after the colon. Thisproperty name is applied to whatever object is handed to

the templatewhen it is asked to render, using the data to expand variablecontent. With this template in place, our processPosts functionchanges to:

函數 WinJS.UI.getControl 的參數是承托控件的元素,這裡就是模闆的div,getControl() 傳回控件對象,實質是 JavaScript 對象,帶有控件的狀态和行為的對象。這裡的行為就是每一項進行渲染時所消化的模闆執行個體方法,就像剛才提到的 createElement 代碼那樣。模闆的渲染函數是一個異步哈書,是以也需要 promise 一個函數,這裡是添加文章資料的過程。運作我們的更新程式所産生的輸出與前面的過程一緻,但因為模闆的縮進就會看起來更清晰。在處理樣式的處理時候,在HTML中編輯好模闆會比

createElement 裡面寫簡單很多。

The call to WinJS.UI.getControl function takes the elementassociated with the control, our template div in this case, andreturns the JavaScript object associated with it that is acting as acontrol. This control brings with it state and behavior. The behaviorwe

want is the render function which stamps out an instance of thetemplate for each item we pass in, just like our createElement codewas doing before. This happens asynchronously in the case of thetemplate's render function, so we use a promise to append the

newlycreated element to our set of posts. Running our updated programproduces output that looks exactly the same as before, but ourintent, with templates, is getting clearer. It's easier to edit thetemplate in the HTML than it is to write more and more complicatedcreateElement

code as our styling and functionality grow.

不得不說,現在程式的樣子離我們想像中的視窗應用程式差很遠,清單内容太多了。實際上,多數 RSS Reader 隻是會列出清單然後讓你選擇。我們也應該這樣做,使用自帶的ListView 控件做就好。

But our big list of all the content isn't as friendly as we want aWindows app to be. In fact, most RSS reader apps show a list of itemsand then let you select one to read. We can do that, too, using thebuilt-in ListView control.

除了模闆控件和固有的控件外,尚有 WinJS内建的若幹控件可用,例如 ListView 便是一個不錯的控件,能夠把資料渲染成為 Grid(表格)或 List (清單)。本例中是 Grid 布局。Grid 布局可以有效地分組、組織相關的資料。Grid 裡的每一項又是模闆來的,這正是利用了模闆的原理。不妨想像一下,首頁出現時候我們不打算顯示全部内容,隻要求顯示标題,将多個标題形成一清單,文章的清單。通過點選便可以看到全文内容。為此,default.html 添加了 ListView 控件,形如:

In addition to the Template control and the HTML intrinsiccontrols, WinJS has several other built-in controls. For example, theListView control is a useful control that knows how to arrange datainto a grid or a list and, in the case of the grid layout, canorganize

data into groups of related-data. Each item in the grid isan expansion of a template, as we've already seen. For example,imagine that we want to create a list of posts, but instead ofproviding the full content on the first page, want to click on anentry to

see the content. Adding a ListView to default.html lookslike this:

通過聲明data-win-control 即可建立 ListView 控件,具體參數可透過data-win-options 屬性其“名稱-值”的結構,傳入到ListView構造器(這是可選的參數)。本例中,ListView的每一項依然使用模闆來決定它顯示的值(沒有内容的修改版本)和布局的類型(預設為grid layout)。指定 ListView 資料的方式仍然是我們熟悉的:

Here we create the ListView control declaratively using"data-win-control". Also, use the data-win-optionsattribute as a set of name-value pairs that we pass as an optionalparameter to the ListView constructor. In this case, we declare thetemplate want to

use for each item (a trimmed down version withoutthe content) and the kind of list layout we want (grid layout is thedefault). Populating the ListView with the data isn't very differentfrom what we've done so far:

這一步,我們沒有建立模闆執行個體,而是建立data清單然後交給 ListView,即可自己渲染模闆。值得一提的是,ListView 是一個聰明的控件,它會自動渲染那些實際顯示的控件,現在我們建立 ListView 并填充資料:

This time, instead of creating an instance of our template foreach item as we process it, we build up a list of data to hand to theListView, which itself renders the template for us. But the ListViewis much smarter about it, rendering only the template for

items thatare actually visible. Now that we created our ListView and populatedit with data, we get:

運用JavaScript建構你的第一個Metro式應用程式(onWindows 8)(二)

We now have half of an RSS reader. We still need the other half –that part where you can actually read the content. The next topic inthis series, Enhancing the presentation of your app, demonstrates howto complete your first Metro style app using JavaScript

by adding areading pane, and using a Microsoft Visual Studio template that givesyour app the personality of Windows.

繼續閱讀