skip to Main Content

Is there any idea on how to trigger / detect a changement on a javascript variable ?
the mail goal is to show on every change , the new value of the variable in a span .

I searched on the internet but I found that there is no event or Eventlistner that works with variable

2

Answers


  1. Object.defineProperty(globalThis, 'some_value', {
      set(value) {
        console.log('some_value set to: ', value)
      }
    });
    
    some_value = 3
    
    //some_value set to:  3
    
    some_value = 2
    
    //some_value set to:  2
    

    Granted this works if your variable in global.

    Login or Signup to reply.
  2. You may utilize this vanilla JS solution that @twalow has suggested.

    But if you want to dive deeper into reactive programming try this stackblitz out

    The snippets:

    TS:

    // Import stylesheets
    import { interval, startWith, Subject, tap } from 'rxjs';
    import './style.css';
    
    // Write TypeScript code!
    const appDiv: HTMLElement = document.getElementById('app');
    
    const subject = new Subject();
    
    subject
      .pipe(
        tap((value) => {
          appDiv.innerHTML = `<h1>TypeScript Starter ${value}</h1>`;
        })
      )
      .subscribe();
    
    /**
     * pretending subject value changes
     */
    interval(2000)
      .pipe(
        startWith(-1),
        tap(console.log),
        tap((value) => subject.next(value))
      )
      .subscribe();
    

    HTML:

    <div id="app"></div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search