Home > OS >  Do I need to keep those variables global?
Do I need to keep those variables global?

Time:06-24

Once I reached out of scopes, from events, I need to keep referencing variables that was declared in the parent scope. In below code, fitAddon. In order to prevent JS's GC to clean up my variable, do I need to keep it global like below? this isn't much clear to me.

// do I need to keep this to use in handleResize() event or
// it would be fine if it was local, i.e., same scope as
// it was initialized?
 let fitAddon: FitAddon;

export const Terminal = () => {

  const id = 'xterm-container';
  useEffect(() => {
    const terminal = new TerminalType({
      cursorBlink: true,
      cursorStyle: window.api.isWindows ? "bar" : "underline",
      cols: DefaultTerminalSize.cols,
      rows: DefaultTerminalSize.rows,
    });

    fitAddon = new FitAddon();
    terminal.loadAddon(fitAddon);
    
    terminal.open(document.getElementById(id) as HTMLElement);
    fitAddon.fit();
    

    function handleResize() {
      fitAddon.fit();
    }

    window.addEventListener('resize', handleResize);

    return () => {
      return window.removeEventListener('resize', handleResize);
    }
  }, []);

  return (
    <div id={id}></div>
  )
}

CodePudding user response:

No, you don't.

As long as the listener exists:

window.addEventListener('resize', handleResize);

the callback will not be garbage collected. Since the callback references fitAddon, fitAddon will not be garbage collected either, no matter where it's declared. So, feel free to declare it inside the effect callback.

const fitAddon = new FitAddon();
terminal.loadAddon(fitAddon);
// ...
  • Related