chrisdavies/rlite

Implement Hash routing but leaving the root location alone.

Mr-Ruben opened this issue · 0 comments

Apologies if this is not the place to put this, but I have spent some time trying to work around this issue and I'd like to share the solution so others don't waste their time.

There is no 'real' issue here (the rlite code is fine). It is more my lack of understanding of how it works, and in particular, of a part of the documentation.

The documentation proposes this to enable hash routing

// Hash-based routing
function processHash() {
  const hash = location.hash || '#';

  // Do something useful with the result of the route
  document.body.textContent = route(hash.slice(1));
}

window.addEventListener('hashchange', processHash);
processHash();

And the issue is that the function gets called on the root location immediately after you call processHash(), so if you had something displayed in the page, it all goes away and gets replaced by "" (nothing).

// on the root location, hash.slice(1) == ""
// so "" gets injected on the page and whatever you had on it goes away
document.body.textContent = route(hash.slice(1));

I found out that you only need to modify that a little to 'leave alone the root location'.

// Hash-based routing
function processHash() {
  const hash = location.hash || '#';


  var afterHash=hash.slice(1);
  console.log(`processHash has been called by "${afterHash}"`);
  
  // Do something useful with the result of the route
  // v1: The --output-- of the function gets injected on the page
  //document.body.textContent = route(hash.slice(1));

  // Do something useful with the result of the route unless is the Root location
  // v2: Just run the function assigned to the route
  if (afterHash!=""){
    route(afterHash);
  }
}

window.addEventListener('hashchange', processHash);
processHash();