简体   繁体   中英

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 ??

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.

Crossroads.js gives crossroads.addRoute(pattern, [handler], [priority]); API to add route patterns. However, when the first time you load the page Crossroads does not automatically initiate the parser to check against the url of the page. You need to add crossroads.parse(document.location.pathname); on you document load to trigger the route. Check out Crossroads.js Tutorial .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM