If you’ve spent any time at all browsing the Windows Store, you may have noticed that there are more than a few apps that show up with the default store logo, which is a simple box with an X through it. The default logo included with the Visual Studio project templates is intended to look unfinished, so that developers will hopefully replace this logo with one that’s appropriately branded for their app. Here’s what one of these apps looks like (I’ve obscured the name of the app to avoid embarrassing the developer):
Notice that the app doesn’t have a great rating. Not necessarily a direct result of not having a nice store logo, but it doesn’t leave a great impression with potential customers.
In this installment of Windows 8: What I’ve learned, I’ll discuss a bug in my app that came from a poor understanding of the underlying template I’d built on.
Getting Started with a Template
To jump start the development of my Windows Store app, Community Megaphone, I used the Grid App JavaScript template, shown below:
I’m a big fan of reuse wherever possible, so in this 6th installment of my Windows 8: What I’ve Learned series, I’m going to share a tip on how you can essentially get some great features for your app, with very little effort, by leveraging an app that ships with every copy of Windows 8.
The Maps app
Windows 8 machines will ship with several handy apps included, such as the Mail app, the People app and a few others. One of the more useful apps is the Maps app. It can, with the user’s permission, use location features built into the machine (GPS, or network-based location services) to find your current location, integrated search for finding a desired address or point of interest, and built in support for directions, traffic, etc. You can see a screenshot of the maps app below:
In this, the 5th, installment of Windows 8, What I’ve learned, I’m going to share a single line of code that can make your search-enabled Windows Store app absolutely awesome!
Start by enabling Search
For starters, if you haven’t enabled the Search contract in your app, you probably should. Unless your app is a game or other kind of app that has no content to search, implementing the Search contract will enable your users to more easily find content in your app, whether it’s running or not, and allow them to do so via a consistent UI that’s part of Windows 8 itself:
As most of you may have figured out, I’ve been doing a fair amount of Windows 8 development over the last year or so, much of it focused on HTML5, CSS3, and JavaScript apps. In this 3rd (whoops! It’s the 4th, not 3rd) installment of my Windows 8: What I’ve Learned series, I’ll share some tips on using the Windows Simulator for testing your Windows Store apps.
In this, the third, post in my series “Windows 8: What I’ve learned,” I’ll share how the behavior of script loading and unloading in some Windows 8 Metro app templates require a different approach to using setTimeout for timers.
Background
I recently had the opportunity to spend some more quality time with the Visual Studio 2012 release candidate, building a Windows 8 app for some of my teammates who focus on Windows Azure, Brian Hitney, Peter Laudati, and Jim O’Neil. You can see a screenshot of the app to the left.
One of the really cool things that these guys have built on top of Windows Azure is the Rock Paper Azure Challenge, an contest to see who can code the most effective online bot to play the game Rock, Paper, Scissors in the cloud. Cool prizes are available, from Best Buy gift cards, to Windows Phones to XBOXes and Kinects.
For TechEd North America this week, they came up with a very special contest, called Beat The Gu. The idea is simple…Scott Guthrie (whom most of you probably know now runs the Azure team), has a RockPaperAzure bot, and TechEd attendees could compete to see who could beat his bot (with a top prize of a 60″ LCD TV).
One of the features that the Rock Paper Azure Challenge provides is a set of leaderboards for all of the various contests that are currently running, with the data accessible via the OData protocol. This makes it super-simple to grab the data in a Windows 8 Metro style app as either XML (ATOM-Pub format) or JSON. I chose to build the app using HTML and JavaScript, so JSON format was perfect.
I’ll be sharing more details on the app and what went into it in a future post, but for now I want to focus on one of the things that bit me during the development process, namely using setTimeout to create a timer.
What I Learned
For the Rock Paper Azure Leaderboard app, I used the Navigation app template, which consists of a default.html page containing a div that becomes an instance of the PageControlNavigator class, which is defined in a script file called navigation.js. Basically this control provides an easy way to dynamically load fragments of markup, CSS and script referred to as Page controls at runtime. And the way that script resources are loaded and unloaded is a little different when using this template, as we’ll see in a bit. You can read more about how single-page navigation works here.
One of the most important features was for the leaderboard information on the home page to be refreshed periodically, since the contest takes place in rounds and after each round, the position of the players will typically change. Since I was using HTML and JavaScript to build the app, the natural way of doing this was to use JavaScript’s setTimeout function to periodically refresh the data.
In earlier versions of the app, I had code in the home page’s ready function that would call a function in my data.js file (modeled after the pattern in the Grid app template) to retrieve a WinJS.Binding.List with the leaderboard data, then bind that data to a ListView on the page. Once all that was done, I would call setTimeout, passing it the name of the function to refresh the data, along with the timeout duration, something like this:
Essentially, the code above will call a function named dataUpdateLoop after 30 seconds. This works great…as long as you stay on the home page.
Although Windows 8 apps written in HTML and JavaScript use standards-based technologies, there are some subtle differences in how the JavaScript and CSS files are loaded (and unloaded, importantly) when using the Navigation app template. With a web site, when you switch to a different page, the DOM is unloaded, and any scripts that were running are no longer in scope. The new page is then loaded, along with any scripts it references.
In an app based on the Navigation template, script loading is a little different. When I run the app, all of the scripts and such required to display the homepage are loaded, as shown in the Solution Explorer screen capture to the left. The base.js and ui.js files are part of the WinJS library, and will always be loaded in a Metro style app (they’re referenced in default.html). default.js and navigator.js are loaded by default.html, and provide support functionality for the entire app, since default.html acts as a parent container for the whole app. settingsUtil.js and searchResults.js are also loaded by default.html, and support the Settings pane and Search contract, respectively.
The remaining JavaScript files, data.js, home.js, and converters.js, are loaded by home.html, which is a Page control that is loaded automatically when the app starts up. Now let’s take a look at what happens when we go to a different part of the application, for example, we can visit the player details page by tapping or clicking on one of the player tiles on the leaderboard:
When the details page loads, we see the screen to the right, which shows us the details for the selected player, including their current place, number of wins and losses and ties, total points, and the date and time of their last match. But of greater interest is what happens with our scripts. If we take another look at the Solution Explorer, we’ll see that another script has been loaded, playerDetails.js, as shown below:
In addition to the new JavaScript file being loaded, notice what didn’t happen…none of the previously loaded scripts were unloaded. BUT…the controls on the homepage (most critically the ListView control containing the leaderboard info) are no longer instantiated. The impact of this, as I discovered in testing the application, is that the timer I set in the code above continues executing, but because leaderListView is no longer instantiated, the dataUpdateLoop function will throw an exception.
Suffice it to say, this was not an acceptable result. I still needed to update the leaderboard on a regular basis, but having the app throw exceptions or crash if I tried to look at the details or use other functionality in the app was not OK.
The Solution
I’m sure there are probably any number of ways to work around a problem like this, but here’s what I came up with (I welcome suggestions for a more elegant or robust solution in the comments). The key is to clear the timer when you move to a different page, and restart the timer when you come back to the home page. Conveniently, JavaScript includes a function for just this purpose, called clearTimeout (there’s a corresponding version for setInterval as well if you’re doing timers that way). But you need to do a little more work in order to use it. clearTimeout requires you to provide it with the ID of the timer you want to clear, which conveniently is a return value of the setTimeout function when called (in my code above, I was simply ignoring this value).
To implement this, I refactored my code as follows:
In the bold section of the code above, I’m capturing the ID of the timer that I’m creating with setTimeout, and storing it as value named “currentTimeoutId” in my local settings. That allows me to access the ID later if I need to clear the timer. I’ve also modified the code to include a check of another setting, refreshData, which is defined in settingsUtil.js, and is a boolean value indicating whether or not to perform the refresh. I’ve also moved the refresh interval into a setting which is likewise exposed by settingsUtil.js. To cancel the timer when navigating to another page, I simply add the following code to the function that’s mapped to the ListView’s oniteminvoked event:
1: function itemInvoked(args) {
2: args.detail.itemPromise.done(
3: function (item) {
4: if (appdata.current.localSettings.values["currentTimeoutId"]) {
In the bold section of the code above, I’m testing whether I’ve captured an ID from a call to setTimeout, and if so, I’m calling clearTimeout and passing in the relevant timer ID. That’s all there is to it!
Summary
When using JavaScript to write an application, whether for the web, or for a Windows 8 app, you need to be careful to understand the scope in which your code is executing, as well as when that code is loaded and unloaded. The Windows 8 Metro app development environment helps you by including best practices, such as wrapping your page code inside a self-executing anonymous function, to help you avoid problems with variable name collisions, etc. The Navigation template is a great place to start because it provides some key infrastructure (including a consistent back button users can use to go back to the previous page) to help you help your users find their way around your app. But you need to keep in mind that script loading in a Metro style app behaves somewhat differently when using the Navigation template to implement single-page navigation.
Note that this tip also applies to the Grid App and Split App templates, since they use the same single-page navigation pattern using navigator.js.
I hope you found this tip useful…if so, please share with your friends and colleagues!
I’ve been playing quite a bit over the last few days with the new Windows 8 Release Preview, as part of a special team project I’m working on with some of my fellow DEs. One of the areas I was working on is doing some simple databinding using a ListView control in a JavaScript Metro style app based on the Navigation App template. In this second installment of my Windows 8, What I’ve Learned series, I’ll give you a tip that may help save you some pain and troubleshooting time when declaratively associating an ItemTemplate for a ListView control inside a page fragment.
I was able to very easily create an array with a couple of objects, each with a couple of properties, and then bind those to the ListView by passing the array to the constructor of the WinJS.Binding.List object, which gave me a List object with a dataSource property that I could assign to the ListView’s itemDataSource property in the ready() function of home.js, like so:
So far, so good…when I ran the project, the data showed up, in JavaScript object style, as expected. But since that’s not a very interesting way to display data, I of course needed to add an ItemTemplate, similar to the following:
Once I had my template declared (note the data-win-control attribute that tells WinJS to instantiate this as a BindingTemplate), I had to tell my ListView about it, which I could do either programmatically or declaratively.
TIP: If you look at either the Grid App or Split App JavaScript templates, both show examples of assigning a template to a ListView programmatically.
I find declarative syntax a bit simpler, so I wanted to do it that way. In previous demos I’ve done, the syntax looked like this:
I dutifully added the data-win-options attribute to my ListView markup, ran the project again, and…nothing. The underlying data was still being rendered as a JavaScript object.
I spent a couple of hours pulling my hair and making little changes to the code before it finally dawned on me to check the ListView quickstart documentation, and lo and behold, it turns out that the declarative syntax above doesn’t work when your markup is part of a page fragment, which is what you get as part of the Navigation App template. Instead, you need to use the following syntax:
The “select” will walk the DOM to resolve the reference, while the direct id reference in the first example won’t work because the fragment markup hasn’t been added to the DOM by the time that the resolution takes place.
So if you’re working with ItemTemplates declaratively in page fragments, be sure to use the “select(‘#templateId’)” syntax to associate your template with your ListView.
Today, I’m kicking off a new blog series, which I’m calling Windows 8: What I’ve Learned, or W8WIL for short. I’ve had the good fortune of spending some quality time with the Windows 8 Consumer Preview release, and there are plenty of little things that can make your life easier as a developer, and I’ll share those in this series.
In this first installment, I want to share some coolness in working with AppBars in your JavaScript Windows Metro style apps. For those of you who haven’t yet started playing with the new app types (if you haven’t, you can grab both the Consumer Preview release, and the Visual Studio 11 beta bits here), the AppBar is a common location for commands for users to interact with content in your app. Below is an example of one of the neat apps that’s currently available in the beta Windows Store, called Physamajig: