-3

Template literal doesn't update even after I rerun the code. I have logged out the object and the value is indeed changing.

let store = {
  txt: 1337,
  txt2: 1837
};

let pages = [
  {
    name: "page1",
    show: true,
    template: `
    <p>This is page1 ${store.txt}</p>
    <button onclick="reactiveChange(store.txt, 1473)">Change store!</button>
    <button onclick="changePage('page2')">change page</button>
    `,
  },
  {
    name: "page2",
    show: false,
    template: `<p>This is page2 ${store.txt2}</p>
    <button onclick="reactiveChange(store.txt, 6537)">Change store!</button>
    <button onclick="changePage('page1')">change page</button>
    `,
  },
];

let render = (() => {
  let app = document.getElementById("app");
  let check = pages.filter((page) => page.show === true).length === 0 ? false : true;
  if (!check) console.error("No page is set to true");
  else app.innerHTML = pages.filter((page) => page.show === true)[0].template;
});

window.onload = render

let reactiveChange = (from, to) => {
    from = to
    render()
}

let changePage = (pageName) => {
    pages.map(page => page.show = false)
    pages.filter(page => page.name === pageName)[0].show = true;
    render()
}
<script src="app.js"></script>
<div id="app"></div>
Dharman
  • 30,962
  • 25
  • 85
  • 135
EMILO
  • 271
  • 4
  • 12
  • 4
    Do not add spam text to your post to get around the requirement that asks you to explain more of the problem - instead, please *actually explain the problem in more detail*. – CertainPerformance Dec 21 '20 at 06:31
  • As the code seems to be in the body of the script, how exactly are you "rerunning" it? – Teemu Dec 21 '20 at 06:34
  • The render function is called after the changePage and reactiveChange functions. – EMILO Dec 21 '20 at 06:35

1 Answers1

1

The value of a template string does not update automatically. It's just a static string after it's been defined.

But you can make them getter functions to make them update whenever you refer to them:

let pages = [
  {
    name: "page1",
    show: true,
    get template() {
      return `<p>This is page1 ${store.txt}</p>
      <button onclick="reactiveChange(store.txt, 1473)">Change store!</button>
      <button onclick="changePage('page2')">change page</button>`;
    }
  },
  {
    name: "page2",
    show: false,
    get template() {
      return `<p>This is page2 ${store.txt2}</p>
      <button onclick="reactiveChange(store.txt, 6537)">Change store!</button>
      <button onclick="changePage('page1')">change page</button>`;
    }
  },
];
Hao Wu
  • 17,573
  • 6
  • 28
  • 60