📎 Webclip
A Javascript router in 20 lines
The post shows how to build a small client-side router with hash URLs and a view container identified by view. Routes are registered in an object, then rendered on load and hashchange by reading the current hash and swapping in a template.
It then extends the router with one-directional data binding using Object.observe(). A route controller can change its data after render, and the router reruns the template so the page updates automatically.
Reading notes#
- The idea comes from earlier posts about writing a template engine in 20 lines.
- The router uses
<script type="text/html">templates so the browser does not parse them. - Hash URLs are used instead of the HTML5 History API.
- Route changes are handled with
onhashchange, and page load is handled withonload. - Routes are stored in a
routesobject through aroute(path, templateId, controller)function. - The controller pattern is described as mimicking AngularJS.
- The router looks for a
viewelement as the render target. - The first version renders the selected template into
el.innerHTML. - A second version adds
Object.observe()so controller changes trigger rerendering. - The data-binding example updates
moreTextafter asetTimeout. - The post says the final version is 28 lines without comments and still lacks parameter support.
