Routing JS to multiple page classes

I’d like my blog.js to execute on the blog and on the archive/category listing.
Basically, I need one route to execute on multiple page classes.

I did manage to come up with a solution. However, I’m unsure if this is the correct way to do it.

// import local dependencies
import Router from './util/Router';
import common from './routes/common';
import home from './routes/home';
import blog from './routes/blog';

// Create a reference to to blog.js
const archive = blog;

/** Populate Router instance with DOM routes */
const routes = new Router({
  // All pages
  common,
  // Home page
  home,
  // Page for posts listing
  blog,
  // Archive page using blog.js
  archive,
});

// Load Events
jQuery(document).ready(() => routes.loadEvents());
1 Like

According to the Router.js shipped with sage 9,
the <body> classes of the page are used for determining the route class.

So maybe a common class name (and route) can be used for both pages.

1 Like

Wow, I didn’t even think about adding a class name used on the pages I want to route the JS to.

But what do you think about my current solution? Could there be issues with such solution?

If your existing solution works it’s probably fine, but IMO defining a custom class for the functionality you want those pages to share would be a more reliable solution: It makes your code clearer and more readable, and also makes it much easier to have JS that runs on blog but not on archive, or visa-versa.

2 Likes