Listening for variable changes in JavaScript

后端 未结 22 3442
自闭症患者
自闭症患者 2020-11-21 06:57

Is it possible to have an event in JS that fires when the value of a certain variable changes? JQuery is accepted.

22条回答
  •  生来不讨喜
    2020-11-21 07:24

    This is an old thread but I stumbled onto second highest answer (custom listeners) while looking for a solution using Angular. While the solution works, angular has a better built in way to resolve this using @Output and event emitters. Going off of the example in custom listener answer:

    ChildComponent.html

    
    

    ChildComponent.ts

    import {EventEmitter, Output } from '@angular/core';
    
    @Output() myEmitter: EventEmitter = new EventEmitter();
    
    private myValue: number = 0;
    
    public increment(n: number){
      this.myValue += n;
    
      // Send a change event to the emitter
      this.myEmitter.emit(this.myValue);
    }
    

    ParentComponent.html

    
    

    ParentComponent.ts

    public n: number = 0;
    
    public monitorChanges(n: number){
      this.n = n;
      console.log(n);
    }
    

    This will now update non parent each time the child button is clicked. Working stackblitz

提交回复
热议问题