How to prevent errors with binding nested values with null RRS feed

  • Question

  • I have a "user" property in my bind context, that can also be "null" if no user is logged in.

    When I now have HTML code like this:

    <span data-win-bind="textContent:user.name"></span>

    This will fail if user ever becomes "null". How to prevent that sort of thing with WinJS?

    Wednesday, June 4, 2014 10:36 PM


  • This is a case where you need a custom converter function, which you inject using a binding initializer. The conversion function can perform a check for user being null and then insert a suitable default.

    Here's how. First, define your conversion function:

    function usernameConverter (user) {
        if (user !== null) {
            return user.name;
        return "invalid user"; //Use a default here.

    Then create a binding initializer from your converter using WinJS.Binding.converter; best practice is to put it in a namespace so that WinJS.Binding.processAll can find it:

        usernameInitializer: WinJS.Binding.converter(usernameConverter),

    Then specify this initializer in your markup:

    <span data-win-bind="textContent: user Initializers.usernameInitializer"></span>

    This will make sure that your username function is called as part of the binding relationship, allowing your null check.

    For more, refer to Chapter 6 of my free ebook that goes into details on data binding, converters, and initializers.


    Author, Programming Windows Store Apps with HTML, CSS, and JavaScript, Second Edition, a free ebook from Microsoft Press.

    Wednesday, June 4, 2014 11:23 PM