locked
How to prevent errors with binding nested values with null

    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 04, 2014 10:36 PM

Answers

  • 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:

    WinJS.Namespace.define("Initializers",
        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.

    Kraig

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




    Wednesday, June 04, 2014 11:23 PM