Patterns for ‘using’ statements in WinJS

January 28th, 2013 11:13 AM ∙ Dibbs ∙ 2 Comments

I’ve been working on Windows 8 HTML & JavaScript applications for a while now and just today it hit me that I could be doing a part of my coding style for those applications a bit differently. Basically in WinJS you sometimes need to alias Windows objects because of the lengthy namespace Microsoft has given those objects by default.

For example if you want to check the Network Connectivity Level, you’d use the enum located in Windows.Networking.Connectivity, meaning your IF statements would look like this:

if (currentLevel === Windows.Networking.Connectivity.NetworkConnectivityLevel.internetAccess) { }

Now that does not look very fun to type, does it? One of the patterns I’ve been using to alleviate this is to create shortcut variables that point to these “namespaces”. Basically think of it as a using statement like this in C#:

using NetworkLevel = Windows.Connectivity.NetworkConnectivityLevel;

…would be this in JavaScript:

var NetworkLevel = Windows.Networking.Connectivity.NetworkConnectivityLevel;

Styling your code like this would make your code a lot easier to deal with all around because now you would just do the same IF statement like this:

if (currentLevel === NetworkLevel.internetAccess) { }

Ten times better, right? Well just today I was thinking we could use a pattern more familiar to us veteran JavaScript Web Developers where we actually can pass global objects into a self-executing anonymous function (as found in most all WinJS files) as parameters. This would look like this:

(function (NetworkLevel) {
    "use strict";

})(Windows.Networking.Connectivity.NetworkConnectivityLevel);

…compared to our original pattern of:

(function () {
    "use strict";

    var NetworkLevel = Windows.Networking.Connectivity.NetworkConnectivityLevel;

})();

I think that while as a web developer I might like the thought of the new pattern better, I would imagine this could get ugly really quickly if you have to alias a lot of objects. Therefore I think simply because of style I would generally stick with our original method using a “var” statement to create the alias. However, it is really nice that JavaScript provides us all these different ways of accomplishing the same task though. What do you think? Which looks better to you?


Eight.js: The Windows 8 JavaScript Toolkit

January 21st, 2013 9:05 AM ∙ Dibbs ∙ Leave a Comment

Just this weekend I was working on polishing up a Windows 8 application I’ve been working on in my free time and decided to pull together some of the more useful functions I’ve been using into a library. Hopefully others will be able to benefit from some of these shortcuts all bundled into one small file.

I still have some cleanup work to do on the script, and obviously some documentation, but the project is live and Beta ready. You can check the project out on Codeplex here: http://eight.codeplex.com/.

The CodePlex page does the library more justice, but here’s a quick summary of some of the features I think are most awesome:

  • Logging: A set of functions for logging messages throughout the lifetime of the application to a cache. The first time the log function is called, a hot spot is created in the lower right hand corner of the app which is invisible until clicked/tapped. When it is tapped, a window will come up with the full log and a button for you to copy the log messages. I thought about hooking into the share contract, but its not as easy as it looks especially when your app is already using sharing.
  • Messaging: A set of functions for displaying alerts and confirmation prompts to the end user. These replace some of the functions that you might find “missing” if you’re moving from browser-based JavaScript development including: window.alert and window.confirm. Both of Eight.js’ replacements are asynchronous however, so still a bit different. I’ve also implemented a queuing system so that you can be sure you won’t get an app crash from trying to show another message when the user hasn’t cleared out the last message you presented.
  • Networking: A set of functions for checking the current levels of network access and network access types on the device. Provides functions for checking if you’re on WiFi, Ethernet, and simply checking if you’re actually on the internet.

The library also has some string manipulation functions which are always handy to have around. If you’ve worked a lot with C#, they’ll all seem pretty familiar.

I’ll try to make some time to go through and break down some of the more complex functions in later blog posts too. That way not only will you have saved time by being able to use this library, but you’ll understand what it’s doing as well!

Let me know what you think, especially if you have any suggestions or ideas for additions to the library and I hope you enjoy!


Using built-in icons in your WinJS app

December 12th, 2012 12:32 PM ∙ Dibbs ∙ Leave a Comment

If you’ve been doing some work in Windows 8, you no doubt have found a need for an icon here or there. There is a great list of icons you can use for the AppBar but wouldn’t it be nice if you could use those icons and more elsewhere?

By now I bet you’ve guessed correctly that you can! It’s really pretty darn simple.

  1. Go to the Sego UI Symbol icon list and pick out the icon you want to use.
  2. Take note of the text next to the icon, which will be something like “U+E006”.
  3. To transform this to a usable numeric character reference for your HTML or CSS is simple. The value from above “U+E006” maps to “&#xE006”. You’ll notice all that we did really was swap “U+” for “&#x”.

That is literally all there is to it. You can then use that icon inline in your code like this:

<p>&#E1006;</p>

…and what you’ll get out is a beautiful outlined heart!


A Skeleton for Custom Controls with WinJS

November 11th, 2012 11:13 AM ∙ Dibbs ∙ 1 Comment

If you’ve worked on or are starting to work on a Windows 8 app with relative complexity, you’ve probably encountered a scenario where you thought: “hey, instead of all this repeated markup, this might be better as a control.”

I’ve run into this myself a couple of times and have settled on a fairly solid skeleton using the WinJS libraries to assist where they make sense. Let’s walk through the bones of this gent together.

Introductions all around

I won’t start off at the beginner level here, I’m going to make some assumptions that you already have a basic understanding of how to go about using the WinJS libraries, and how vanilla JavaScript works at an intermediate level.

Below you can see the basic skeleton of a custom TurtlePower control.

(function () {
    "use strict";

    WinJS.Namespace.define("GotDibbs.Controls", (function createClass() {

        var TurtlePower,
            otherGlobals;

        TurtlePower = WinJS.Class.define(
        function constructor(element, options) {
            var control = this;

            if (!element) {
                throw "Element must be provided.";
            }
            options = options || {};

            control.element = element;
            control.options = options;

            control.createVisualTree();
        },
        (function defineInstanceMembers() {

            function setValue() {
            }

            function setDisabled(isDisabled) {
            }

            function createVisualTree() {
                var control = this,
                    elem = control.element;
            }

            return {
                setValue: setValue,
                setDisabled: setDisabled,
                buildControl: buildControl
            };

        })());

        return {
            TurtlePower: WinJS.Class.mix(TurtlePower, WinJS.Utilities.eventMixin)
        };

    })());

})();

As you can see, one of the big concepts I use with frequently is that of the revealing module pattern, created using immediately-executing functions. These patterns really help to keep your code clean and readable.

One brief step to the side for a second: you’ll notice that I name all of my immediately-executed functions. They would otherwise be anonymous and that can cause issues when you’re looking at a stack trace. Who wants to see a listing of “anonymous function > anonymous function > annonymous function”? How helpful is that?

I’m going to skip over the usage of the WinJS.Namespace.define and WinJS.Class.define functions’ core functionality, but you can visit the links inline to see a bit more detail on each.

Now let’s take a step closer and start to break down the control into some of it’s key components.

Stepping into the Constructor

Writing JavaScript using the WinJS libraries really makes you know your stuff when it comes to emulating OOP in JavaScript. If you notice above in the skeleton, we have a function called constructor which takes in a DOM element and an options object. This is where our control’s life begins. When we call WinJS.UI.processAll() in our app and it encounters one of our custom controls created declaratively in the HTML, our constructor function is what gets called to bring our control to life. Note that the function is also called when you instantiate the control programmatically via something a la:

var power = new GotDibbs.Controls.TurtlePower(elem, opts);

So what do we want to do here? Let’s break it down starting from the top.

function constructor(element, options) {

As we’ve already mentioned, the two parameters to this function are a DOM Element (usually a DIV already declared somewhere), and an Options object which allows us to change the behavior of our control from one instance to the next.

var control = this;

Here, if you’re not too familiar with JavaScript, you might get a bit lost, and if you’re not clear on what this line is doing exactly I’d suggest doing a bit of research on the JavaScript this keyword. Basically in the current context all we’re doing is “aliasing” the instance of the control to the variable control. I am a big proponent of “aliasing” the this keyword because it provides more insight as to what exactly you’re expecting this to be.

if (!element) {
    throw "Element must be provided.";
}
options = options || {};

control.element = element;
control.options = options;

In the above section we do a couple of things to make sure our control is being instantiated correctly, and then we cache a reference to both the element and the options that were passed into the function. No big surprises there.

control.buildControl();

The last line actually calls the control instance’s buildControl function which is defined in the instance members that follow the control’s constructor. Let’s head over there now and take a peek at the torso of our skeleton; where the real meat of our control will live.

Getting Fancy with Instance Members

Thanks to the revealing-module pattern, we can see from the defineInstanceMembers function that the three core public functions for this control are: setValue, setDisabled, and buildControl.

The purpose of the buildControl function should seem a bit self-explanatory, but it is basically what handles making sure our control contains the appropriate DOM elements, the appropriate styles, and makes sure the appropriate internal events are handled … well, internally. This function is exposed just so that our constructor can see it and call it. If this were C#, it’d probably actually be private, protected, or internal.

The setValue and setDisabled functions are there to be invoked on an instance of our control from JavaScript after the control’s instantiation. For example say we had another dependent control that when it was set to specific value, we wanted our TurtlePower control to be set to an appropriate value and then disabled. This would then look something like this:

var elem = document.querySelector("#turtlePower");
elem.winControl.setDisabled(true);
elem.winControl.setValue("NinjaFu");

You can see that basically we just invoke the functions directly off of the winControl object defined on the element. Pretty simple, right? Well now what if we need to know when something changes on our control? Let’s hop into that now.

Using Events (and not Data Binding)

Generally when the value of our control (assuming it’s an input control for this instance) is set through the UI or through code, we probably want to know so we can track it’s value through it’s lifetime. This can usually be done generally in one of two ways with WinJS: Binding or Events.

Sadly, I’ve run into about a bazillion problems with data binding in WinJS and therefore tend to avoid it now, especially with controls. Some brief examples:

  • WinJS only provides for one-way binding.
  • Binding functions to a property’s on-change handler right after a call to WinJS.Binding.processAll() seems to immediately invoke the change handler on the wrong instance of the control – assuming you have more than one instance in play.

So wait … if we can’t effectively use binding how ever will we know when a value changes? Well it’s over to the event-based model for now.

Instead of mixing our class with the WinJS.Binding.mixin, we mix it with WinJS.Utilities.eventMixin which automatically adds functions such as addEventListener and dispatchEvent to our class. We achieve this in the return statement at the end of our namespace:

return {
    TurtlePower: WinJS.Class.mix(TurtlePower, WinJS.Utilities.eventMixin)
};

What exactly does this do for us, you ask? This allows us to add a simple call to dispatchEvent to notify any listeners of that event. For example, in our setValue function we would call something like the below to notify listeners that the value has changed.

function setValue(val) {
    var control = this;
    // ... set the value on the control ...

    // Notify listeners
    control.dispatchEvent("change");
}

…and we listen for a change like this….

var elem = document.querySelector("#turtlePower");
elem.winControl.addEventListener("change", function (e) {
    // ... handle on change event ...
});

You might be thinking well let’s just switch to using Knockout.js or some similar library to achieve two-way binding … but it actually can get pretty messy going that route. However, it is an option nonetheless.

Conclusion

What we’ve achieved here is to create a skeleton of a WinJS control conforming to more common and modern web-based JavaScript standards. The patterns used within really help to promote readability – which is essential when creating any reusable and maintainable control. After all what good is converting frequently used code into a control if no one can read it or understand what it is doing? I’d be curious to here if anyone has any feedback and always welcome different approaches!

Categories: .NET, Development
Tags: ,

Visual Studio 2010 Extension Debugging Woes

August 15th, 2012 2:20 PM ∙ Dibbs ∙ Leave a Comment

I recently came back to a Visual Studio extension (vsix) I had created a while back to make some updates. In the time since, someone had cleaned up the project structure a bit.

What was confusing was that when I would try to hit F5 to debug the extension, I did not get what I expected. Instead of the new “experimental” instance of Visual Studio opened with my extension registered and ready to test, I instead got a lovely error stating: “A project with an Output Type of Class Library cannot be started directly.”

I spent a fair bit of time googling around before I found the answer here: http://donovanbrown.com/post/How-to-debug-a-Visual-Studio-Extension.aspx

To summarize, you need to ensure your project is set to open Visual Studio under the Debug setting’s “Start Action”, this is as opposed to just “Start Project” which is what my project file had been somehow changed to.

See the link for a great description and explanation of the problem.