Home > Software design >  How do I get my Javascript to work with all views in Javascript/Handlebars.js
How do I get my Javascript to work with all views in Javascript/Handlebars.js

Time:01-09

Handlebars has a feature where I can load a bunch of subdocuments. Inside the main document.

project

Inside main.handlebars I have my menu items that when clicked will load home.handlebars, license.handlebars, etc. A page reload does happen.

main.handlebars loads my index.js file.

But that JS file will return an error because an element it's trying to access via

const dataFromDB = document.querySelector('.elementFromHome')

is inside home.handlebars

addEventListener is from an element that is in home.handlebars only

Now let's say I click a menu item that loads the license.handlebars. All the elements in index.js will return null if they were in home.handlebars. Any help?

My solution:

I probably could wrap my elements that are needed for each sub-document. In an if statement. So it would check it on each page load. But I looking for a more practical solution. Thank you.

App is using the MEVN stack.

CodePudding user response:

It seems like you could fix this by using optional chaining at node.addEventListener.

Then if dataFromDB is null on that page, you won't get a runtime TypeError by attempting to access the addEventListener property on null.

const dataFromDB = document.querySelector('.elementFromHome')
dataFromDB?.addEventListener('click', () => {
  console.log('click')
})
<button >button from home</button>

  • Related