Client side routing. How does it work?

2019-03-18 18:32发布

I need a client-side routing solution to work with a chrome app. I've researched several and crossroads.js seems like a good fit. When I include it in my html file, it doesn't seem to work; that is, if I use code like

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

, the page alerts '123' but if I type '/news/321' in the browser's url bar, it preforms the browser's default action, instead of alerting '321'. What am I doing wrong. (Also, I realize the title is broad, but I believe the difficulties I'm having with crossroads.js are more general than crossroads.js in particular. It is given as an example.)

2条回答
做自己的国王
2楼-- · 2019-03-18 18:36

Use Hasher (by the same author) also.

The documentation on the Crossroads page tells you that you need to use Hasher, (because that will be used for monitoring the widow.location bar.).

So you would also need to use Hasher, and initialise it, then you can add your "Crossroads" routes to Hasher to start monitoring for those particular routes.

//setup crossroads
crossroads.addRoute('foo');
crossroads.addRoute('lorem/ipsum');
crossroads.routed.add(console.log, console); //log all routes

//setup hasher
hasher.initialized.add(crossroads.parse, crossroads); //parse initial hash
hasher.changed.add(crossroads.parse, crossroads); //parse hash changes
hasher.init(); //start listening for history change

//update URL fragment generating new history record
hasher.setHash('lorem/ipsum');

http://millermedeiros.github.com/crossroads.js/

查看更多
混吃等死
3楼-- · 2019-03-18 18:46

The command parse tells crossroads to have a look at the string and do an action based on it.

So in the case of crossroads.parse('/news/123'); it will always use /news/123.

Since you want crossroads to parse what you have in the browser address bar, you'll need to use that value in the parse method:

crossroads.parse(document.location.pathname);
查看更多
登录 后发表回答