routing.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * @file
  3. * Contains the router code and route definitions
  4. *
  5. * Inspired by Joakim Beng's example.
  6. *
  7. * @see http://joakim.beng.se/blog/posts/a-javascript-router-in-20-lines.html
  8. */
  9. // The routes object.
  10. var routes = {};
  11. // The route registering function:
  12. function route(path, controller) {
  13. routes[path] = controller;
  14. }
  15. // The router.
  16. function router() {
  17. // Current route url (getting rid of "#" in hash as well):
  18. var url = location.hash.slice(1) || "/";
  19. // Get route by url:
  20. var currentRoute = routes[url];
  21. var context = null;
  22. var templateName = null;
  23. // Do we have both a view and a route ?
  24. if (contentElement) {
  25. if (currentRoute) {
  26. // Render route template with Handlebars:
  27. context = new currentRoute();
  28. templateName = (url === "/") ? "home" : url;
  29. contentElement.addEventListener(EVENT_TEMPLATES_LOADED, function () {
  30. console.log('templates', templates, 'name', url, templateName);
  31. contentElement.innerHTML = templates[templateName](context);
  32. });
  33. }
  34. else {
  35. console.warn("Content found but no route matching", url);
  36. }
  37. }
  38. else {
  39. console.warn("Content not found.");
  40. }
  41. }
  42. // Bind router to browser events.
  43. // window.addEventListener("hashchange", router);
  44. window.addEventListener("load", router);
  45. // Route declarations.
  46. route("/", function () {
  47. console.log('Home controller');
  48. });
  49. route("class", function () {
  50. console.log('Class controller');
  51. this.greeting = "Hello world!";
  52. this.moreText = "Bacon ipsum...";
  53. });
  54. route("species", function () {
  55. console.log('Species controller');
  56. this.heading = "I\"m page two!";
  57. });