Question about the ui updates for the Vite Stackblitz typescript demo?

  Kiến thức lập trình

In the new Stackblitz typescript baseline project there’s a setupCounter() method within counter.ts that looks like this.

export function setupCounter(element: HTMLButtonElement) {
  let counter = 0;
  const setCounter = (count: number) => {
    counter = count;
    element.innerHTML = `count is ${count}`;
  };
  setCounter(counter);
  element.addEventListener('click', () => setCounter(counter + 1));
}

I’ve changed it a little bit so that the string literal that displays the updated count references the passed in count variable.

And the demo still works. We can click the update count button and the count updates.

However if we comment out the line:

//    counter = count;

Which seems non important, the count only updates on the first click. Just curious why this is.

This is the demo.

https://stackblitz.com/edit/vitejs-vite-6qyuol?file=src%2Fmain.ts,src%2Fcounter.ts&terminal=dev

LEAVE A COMMENT