Route Handling Framework for Choo

I’ve made a complementary route handling framework for Yoshua Wuyts’ JavaScript SPA (Single Page Application) framework Choo: choo-routehandler. For those unfamiliar with Choo, it’s a view framework similar to React and Marko, although with a strong focus on simplicity and hackability and working directly with the DOM instead of a virtual DOM (unlike React).

Basically, the motivation for making the framework was that I found myself implementing the same pattern in my Choo apps: To load data before rendering a view corresponding to a route and to require authentication before accessing certain routes. I didn’t find any good way to handle this baked into Choo, even though it has a rather good routing system built into it. It was also tricky to use Choo’s standard effects/reducers system to implement handling of route change, since these are asynchronously triggered and I could end up handling the same route change several times as a result.

After some trial and failure and good old-fashioned experimentation, I found that I could use the standard MutationObserver API to detect that a new route has been rendered, and take necessary action (i.e. require authentication/load data) subsequently.

The flow of events after a route change has been detected by the framework depends on whether the user is logged in or not and whether the route requires authentication. If the route does require authentication and the user is not logged in, the user is redirected to the login page. Otherwise, the data loading flow commences so that the view’s function for loading data is invoked asynchronously and a loading view is rendered until data is fully loaded. Then the view corresponding to the route is rendered, given the loaded data. It may also be the case that the view has no function for loading data, in which case it’s rendered directly and no data loading takes place.

Leave a Reply