Binding Aurelia Routing Rules

Monday, February 22, 2016

Aurelia continues a march towards beta 2 with a big February release.  There are no breaking changes, and the framework still provides features to make building applications easy. One feature I’ve used recently is the navigation model provided by the Aurelia router. I think of the navigation model as an amalgamation of routing configuration with current routing state to provide a data source for navigation menus and other UI components.

The routing configuration comes from the conventional configureRouter method of a view model. For top-level routing, the method might look like the following.

configureRouter(config, router) {
    this.router = router; 

    config.title = "Movies";
    config.map([
        { route: "", name: 'home', moduleId: "movies/list", 
          title:"List", nav:true, settings: { icon: "home" }                
        },
        { route: "about", moduleId: "about/about", title: "About", nav:true },
        { route: "details/:id", name:"details", moduleId: "movies/details" },
        { route: "edit/:id", name:"edit", moduleId: "movies/edit" },
        { route: "create", name:"create", moduleId:"movies/edit" }
    ]);
}

Notice the nav and settings properties in the first RouteConfig entry. The nav property identifies to the router which of the entries are part of the navigation model. The settings property allows us to attach arbitrary data to a RouteConfig entry, data we might find useful when binding to the navigational model in a view. In this example, the setting is the name of a Font Awesome icon. We can use the resulting navigation model in a view like so:

<ul class="nav navbar-nav">
    <li repeat.for="row of router.navigation"
        class="${row.isActive ? 'active' : ''}">
        <a href.bind="row.href">
            ${row.title}
            <i if.bind="row.settings.icon" class="fa fa-${row.settings.icon}"></i>
        </a>
    </li>
</ul>

The navigation model is just one of many features to like about Aurelia.


Comments
Comments are closed.

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!