Search code examples
javascriptjquerynode.jsember.jscrossroadsjs

Crossroadsjs routing: how to use it?


I am facing the same problem as this one as I am trying to figure out how to use crossroads for a few hours now and nothing seems to work. its webiste is just another poor documented site... I think I am probably daft! I wonder if anyone has made it?

html head,

<title>Crossroads</title>
  <script src="js/libs/signals.js"></script>
  <script src="js/libs/crossroads.min.js"></script>
  <script src="js/app.js"></script>
</head>

app.js, just as simple as this,

crossroads.addRoute('/news/{id}', function(id){  
  alert(id);  
}); 

so I try it out on my localhost browser,

http://localhost/crossroadjs/#/news/123

nothing happens. I thought it would be 123??


Solution

  • Crossroads doesn't handle history/state change events from the browser. From their site:

    A routes system shouldn't do anything else besides routing.

    Instead, the site recommends Hasher for this purpose and gives a rather complete looking example:

    //setup crossroads
    crossroads.addRoute('foo');
    crossroads.addRoute('lorem/ipsum');
    crossroads.routed.add(console.log, console); //log all routes
    
    //setup hasher
    function parseHash(newHash, oldHash){
      crossroads.parse(newHash);
    }
    hasher.initialized.add(parseHash); //parse initial hash
    hasher.changed.add(parseHash); //parse hash changes
    hasher.init(); //start listening for history change
    
    //update URL fragment generating new history record
    hasher.setHash('lorem/ipsum');
    

    Alternatively you could use a different history plugin, or write something yourself. But crossroads leaves that part up to you.