123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- /**
- * @file
- * Contains the router code and route definitions
- *
- * Inspired by Joakim Beng's example.
- *
- * @see http://joakim.beng.se/blog/posts/a-javascript-router-in-20-lines.html
- */
- // The routes object.
- var routes = {};
- // The route registering function:
- function route(path, controller) {
- routes[path] = controller;
- }
- // The router.
- function router() {
- // Current route url (getting rid of "#" in hash as well):
- var url = location.hash.slice(1) || "/";
- // Get route by url:
- var currentRoute = routes[url];
- var context = null;
- var templateName = null;
- // Do we have both a view and a route ?
- if (contentElement) {
- if (currentRoute) {
- // Render route template with Handlebars:
- context = new currentRoute();
- templateName = (url === "/") ? "home" : url;
- contentElement.addEventListener(EVENT_TEMPLATES_LOADED, function () {
- console.log('templates', templates, 'name', url, templateName);
- contentElement.innerHTML = templates[templateName](context);
- });
- }
- else {
- console.warn("Content found but no route matching", url);
- }
- }
- else {
- console.warn("Content not found.");
- }
- }
- // Bind router to browser events.
- // window.addEventListener("hashchange", router);
- window.addEventListener("load", router);
- // Route declarations.
- route("/", function () {
- console.log('Home controller');
- });
- route("class", function () {
- console.log('Class controller');
- this.greeting = "Hello world!";
- this.moreText = "Bacon ipsum...";
- });
- route("species", function () {
- console.log('Species controller');
- this.heading = "I\"m page two!";
- });
|