Perform a function based on the hash with director.js

452 Views Asked by At

I am trying to use director.js for the routing on my single page application. The issue is when you go to a page by typing it into the address bar the application does not perform the function that the hash in the routing table is pointed to.

Here is the example on github - If I refresh the page with a hash or direct to a page with a hash nothing shows up in the console. But if I click on one of the links console output is shown. How can I change this code so that if a user directly goes to a link the routing table checks the hash and performs it's matching function from the routing table? Please answer with a methodology that utilizes director.js

<html>
  <head>
    <meta charset="utf-8">
    <title>A Gentle Introduction</title>
    <script src="https://raw.github.com/flatiron/director/master/build/director.min.js"></script>
    <script>

      var author = function () { console.log("author"); },
          books = function () { console.log("books"); },
          viewBook = function(bookId) { console.log("viewBook: bookId is populated: " + bookId); };

      var routes = {
        '/author': author,
        '/books': [books, function() { console.log("An inline route handler."); }],
        '/books/view/:bookId': viewBook
      };

      var router = Router(routes);
      router.init();

    </script>
  </head>
  <body>
    <ul>
      <li><a href="#/author">#/author</a></li>
      <li><a href="#/books">#/books</a></li>
      <li><a href="#/books/view/1">#/books/view/1</a></li>
    </ul>
  </body>
</html>
1

There are 1 best solutions below

1
Matt27 On

I have not used Director but your issue may be the fact that GitHub serves the "raw" files with a mime type of "text/plain". So the Director js code might not be processed as javascript, causing your test page not to work. Try downloading your own copy of Director and link to the local version instead of the one on GitHub.