I've had the services below running for a few years to support Programming Windows Store Apps with HTML, CSS, and JavaScript. Hwoever, given that the books themselves are getting a bit out of date, I figured it's time to shut them down. Using the examples in the books, similar services would be easy enough for you to deploy to a host of your own. Let me know if you have questions.

http://programmingwin-js-ams.azure-mobile.net

http://programmingwin8-js-ch13-amspushnotifications.azure-mobile.net

http://programmingwin8-js-ch13-hellotiles.azurewebsites.net

 

 


In a number of forum questions over the years, I've seen devs struggling with using relative URIs to in-package resources. Typically it boisl down to the difference between something like "images/pix1.jpg" and "/images/pix1.jpg".

These two URIs mean, in the words of Jeremy Foster, "dive into the images folder and find pix1.jpg" and "go back to the root, then dive into the images folder and find pix1.jpg", respectively.

In Windows Store apps, it's helpful to remember that all such in-package 'relative' URIs are shorthands for ms-appx://<package_id>, as in ms-appx://<package_id>/images/pix1.jpg or just ms-appx:///images/pix1.jpg. A leading / on URIs, then, is what really makes the reference an absolute one, rather than a relative one. It just feels relative because you're not specifying a schema.

To be even more precise, a relative URI always must resolve against some base URI, which is defined by the referring document. Where people get tripped up is that when you're using WinJS page controls, such as ms-appx:///pages/somePage.html, then ms-appx:///pages becomes the base URI, and images/pix1.jpg will resolve to ms-appx:///pages/images/pix1.jpg. If you thought you were referring to the root images folder in the project, then you'll likely find the image not appearing at all. If you use /images/pix1.jpg, on the other hand, then you are making an absolute reference from the package root via shorthand, which resolves to ms-appx:///images/pix1.jpg.

The bottom line is that unless you really know that you're making a relative reference to the currently loaded HTML page, use a leading / to get back to your package root.


Some Q&A I've collected recently. Enjoy.
 

Q: I'm trying to bind part of a ListView item template to the result of a method in a class, but the function text itself is appearing instead of the result. How can I make this work?

A. Here's the context for the question. Say we have a simple binding declaration as follows:

<div data-win-bind="textContext: FullName"></div>

And we're binding to a class that looks like this:

var _MyClass = WinJS.Class.define(
    function () {
        this.FirstName = "";
        this.LastName = "";
    },
    {
        FirstName: "",
        LastName: "",
        FullName: function () {
            return this.FirstName + ' ' + this.LastName;
        }
    }
);

The issue is that binding to FullName doesn't execute the function, but just binds to the function object. There aren't problems binding to FirstName and LastName as those are just properties.

The solution here is to make FullName a property as well, rather than a function, which can be done as follows:

FullName: {
    get: {
        return this.FirstName + “ “ + this.LastName;
    }
}

[Thanks to Dominic Hopton]

 

Q. Is it possible from JavaScript to bind to data in a WinRT component?

A. Yes. The trick is that you need to use WinJS.Binding.oneTime as the initializer in the binding syntax. For a full discussion, see Mike Taulty's blog: http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2012/04/26/windows-8-metro-style-bits-of-binding.aspx

 

Q. Is it possible to use WinJS data binding on styles and other non-text elements?

A. Yes it is. In general you can use the syntax data-win-bind="style.<target_property>: <source_property>", and for styles like font-weight and text-decoration that don't work with dot notation you can use []'s as in data-win-bind="style[target-property]: <source_property>".

Phil Japiske has a good post on this subject on Telerik's blog: http://blogs.telerik.com/Windows8Team/posts/13-12-27/setting-html-styles-with-binding-in-windows-8-winjs-apps 


I've seen the question come up on occasion about using WinJS within a webview. This is entirely supported, and has been since the introduction of WinJS–the library always checks whether WinRT is present and adjusts itself accordingly. For example, if WinRT is available, then it will use WinRT app data for saving its settings; if WinRT isn't available, it uses standard HTML5 APIs instead.

This strategy wisely foresaw the day when WinJS was licensed for use in web page. This wasn't originally the case (as the copyright headers in the WinJS files made clear), but with WinJS going open source in April 2014, WInJS can be used anywhere.

When using WinJS, and especially WinJS controls, inside a webview or web page, it's important to remember steps that are included by default within the Windows app templates, most notable the step of calling WinJS.UI.processAll. That is, when you create a new Windows app, the templates in Visual Studio supply the following default activation code:

var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;

app.onactivated = function (args) {
    if (args.detail.kind === activation.ActivationKind.launch) {
        if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
            // TODO: This application has been newly launched. Initialize
            // your application here.
        } else {
            // TODO: This application has been reactivated from suspension.
            // Restore application state here.
        }
        args.setPromise(WinJS.UI.processAll());
    }
};

Clearly, if you're using WinJS outside of an app, then the Windows.ApplicationModel.Activation namespace won't mean anything, so naturally you'll delete all the code inside the onactivated handler here. But if you delete WinJS.UI.processAll then none of your WinJS controls will show up. This can be confusing and might lead to the idea that WinJS doesn't work in a webview. But it does, because in the end WinJS is just a JavaScript library using standard HTML5/DOM to do its work. So just make sure that somewhere you have a line like this:

<script>
    WinJS.UI.processAll();
</script>

 


I've seen this question come up twice lately, once via email and again on StackOverflow. The questions are something like this:

My app has strange behavior with its template bindings with WinJS. When I navigate to a page and then back, everything is fine, but if I navigate to the same page then the bindings get all jumbled and I see only the raw JSON.

I have an app written in JavaScript whose app bar commands navigate to different pages, including the page that's currently loaded. Navigating between different pages works fine, but navigating to the same page (essentially reloading it) loses event handlers on my buttons.

In short, strange things seem to happen when navigating (with WinJS.Navigation.navigate) to the same page that's already loaded. Here's what's happening.

Page navigation in WinJS is just a matter of DOM replacement. When you navigate using the navigator.js file that's part of the Visual Studio templates, the target “page” contents are loaded into the DOM and then the previous “page’s” contents are unloaded. You can see this in navigator.js in the _navigating method. It creates a new element for the page being loaded, renders that fragment therein, and then unloads the old page.

The ready method for the new page, however, is called before the old page is unloaded (this was a change in WinJS 2.0, as WinJS 1.0 unloaded the old page before calling ready). The upshot of this is that when you navigate to the same page that’s already loaded, page.html(A) is in the DOM when you load page.html(B).

As a result, anything you attempt to do in the DOM during the processed or ready methods, which includes adding event listeners or attaching templates, will find the elements in page.html(A) and not page.html(B). That is, when getElementById traverses the DOM it finds elements in (A) first and stops there; locating templates works in the same way, so any data bindings that include templates will get hooked up to the templates in (A).

But then, of course, as soon as you return from the ready method, page.html(A) gets unloaded, so all your hard work is thrown away!

Again, this is a behavior that appears when navigating to the same page that's already loaded, so the solution is to avoid navigating to the same page because it's just fraught with peril. In some cases you can disable the navigation controls in your UI so you can't navigate to the current page. However, that's not always easy to do, so here's a way to wrap your call to WinJS.Navigation.navigate with a check for whether you're already on the target page:

function navigateIfDifferent(target) {
    var page = document.getElementById("contenthost").winControl.pageControl;
    var fullTarget = "ms-appx://" + Windows.ApplicationModel.Package.current.id.name + target;
    if (fullTarget !== page.uri) {
        WinJS.Navigation.navigate(target);
    }
}

This assumes that the PageControlNavigator control that you're using is in a div called "contenthost" in default.html (which is what the VS template gives you). What I'm then doing is building the full in-package URI for the target page and comparing that to the uri of the current page control, which is also a full in-package URI. You could also strip off the ms-appx:// part from the current page URI and compare to the target URI. Either way–you can then replace calls to WinJS.Navigation.navigate with navigateIfDifferent.

On the flip side, there are likely some scenarios where you specifically want to reload or refresh the current page, so a self-navigation seems like a way to do this. It should be fairly obvious, though, that any page initialization you do in ready or processed can be moved into separate methods that you call elsewhere to refresh the page. Remember too that you can call WinJS.Binding.processAll at any time in your code to refresh the data binding–it's not specific to page loading or other initialization procedures.

I'd recommend this as the first choice, because it won't mess with everything else that's been set up in the DOM already, and should perform better than reloading everything. 

However, if you still want to navigate to the same page to reload, then you need to defer the processing you'd normally do in ready to a later time. You could use a call to setImmediate for this purpose (it should work–I haven't tried it directly), but a simpler means (thanks to Guillaume Leborgne) is to make sure you scope any element queries or selections using the page's root element that's passed as the element argument to the ready method. Using this as the starting point, you'll restrict the scope to the newly-loaded page rather than the whole document.

And as a final note, you can always go to the lower-level WinJS.UI.fragments API to do your own page-loading implementation.


With the introduction of universal Windows apps at //build 2014, and the announcement of Windows Phone 8.1 that includes support for writing apps in HTML, CSS, and JavaScript, we do have some resources that are starting to emerge.

First, my newly-released second edition, http://aka.ms/BrockschmidtBook2, is very applicable to Phone apps. I didn't have time to spell out all the differences, but there is a summary of what to watch out for in Chapter 1, namely a few differences in controls and some parts of WinRT that aren't on the Phone.

Second, watch the Building Apps for Windows Blog for material in this area. For example, an upcoming post will spell out the controls story between Windows (WinJS 2.0) and Windows Phone (WinJS 2.1).

Third, Josh Williams and Ryan Salva did a demo session on building a universal app with HTML, CSS, and JavaScript at //build, which you can find on http://channel9.msdn.com/Events/Build/2014/2-540. What you'll see is that they do nearly all of the work in the Shared folder of the VS project, making only one small change at the end of the session to switch the Hub control in the Windows Store app to Pivot in the Phone app…the two controls, in fact, are identical in their API except for the top-level object names, so you just change the names and voila! You're in business.

Finally, there is a post on the Visual Studio blog on universal apps: http://blogs.msdn.com/b/visualstudio/archive/2014/04/08/building-windows-phone-8-1-apps-in-html.aspx.

More is certainly to come.


Programming Windows Store Apps with HTML, CSS, and JavaScript, Second Edition, is now released! You can find this free ebook (PDF, Mobi, and epub) it on http://blogs.msdn.com/b/microsoft_press/archive/2014/04/08/free-ebook-programming-windows-store-apps-with-html-css-and-javascript-second-edition.aspx. Companion content is on http://download.microsoft.com/download/6/6/5/665AF7A6-2184-45DC-B9DA-C89185B01937/Programming_Windows_8_Apps_HTML_CSS_JavaScript_2E_CompContent.zip and the videos are on http://microsoftpressbooks.azurewebsites.net/programming_windows_apps_with_html_2ed/.

I have to say that it's ironic that although the book covers Windows 8.1 and is mostly applicable to Windows Phone 8.1 as well, announcements at //build changed the landscape almost immediately. For one, WinJS is now open source and isn't specific to Windows Store Apps, and WinJS 2.1 for Windows Phone has some differences from WinJS 2.0 for Windows Store apps. Oh well. Guess it's onto the third edition now! Still, I suspect that this book, being free and the most comprehensive, will continue to be the primary WinJS reference, open source or not.

 

 



As of last week I assumed management and content development for the Windows App Builder’s Blog, which I’m sure most of you follow already.

What I’d love to hear from you is this: what content would you like to see on the blog? What questions are you dying to have answered? What ‘inside stories’ from the Windows engineering team would you like to know? Let me know in the comments!


The Semantic Zoom control in WinJS, as you probably know, is basically a control that provides a switching effect between two other controls. Any control that implements the IZoomable interface will work, though in WinJS the only two that do this are the ListView and the Hub. (Implementing the interface is not difficult, though; refer to the HTML SemanticZoom for custom controls sample in the SDK.)

When hosting ListView controls (the most common case), the question can arise about how to size and position the zoomed out view, primarily because the ListView is hosted inside the SemanticZoom control, which sets the position of the ListView itself.

The trick in this case is to have the SemanticZoom control sized to 100% of the desired space, and then use the margins of the .win-surface style on the ListView. The SemanticZoom will honor those margins in its positioning work. Be sure, also, to adjust the height of the .win-surface style as well to prevent scrollbars from appearing when you set the margins.