Tyler
Tyler

Reputation: 839

returning to root page with crossroads.js and hasher.js

I'm just starting out with crossroads.js and hasher.js and am having success parsing most of my routes. What I don't understand is how to get back to the root of the page. I know I'm not saying that right, but here's my issue:

  1. I navigate to http://example.com and I see what I need to see.

  2. I change the hash to http://example.com/#/foo and I do what I need to do to change the DOM.

  3. I try to click back in the browser, and I'm suck here.

Maybe I need to define the "root" route in crossroads? Am I doing something wrong with the history?

Upvotes: 1

Views: 1642

Answers (1)

Jan Stanicek
Jan Stanicek

Reputation: 1281

As I understand you are on halfway in both settings (hasher + crossroads).

Adding route with "root" pattern into crossroads triggers defined handler for this route if the root pattern matches. And handler invokes display root page content.

And second issue is the hasher which must be well configured. See difference between hasher.setHash() and hasher.replaceHash() on hasher doc. Use setHash if you want to keep history and use browser back feature.

The whole process will be:

  1. Change URL by hasher.setHash(new_hash_value), manually enter URL into navigation bar or use back button in browser
  2. hasher recognize that hash has been changed and triggers crossroads for further processing new URL
  3. crossroads parse new hash and invokes display root page (this requires route with root hash pattern)

Prepare hasher to be able listen changes:

function parseHash(newHash, oldHash){
  crossroads.parse(newHash);
}

hasher.initialized.add(initialParse); //parse initial hash
hasher.changed.add(parseHash); //parse hash changes
hasher.init(); //start listening for hash changes

and of course define route for root page to be able invoke display root content:

crossroads.addRoute("", function() {
     // call displaying root page
  });

Upvotes: 1

Related Questions