3

Before I start, I'd just like to say that there are already answered questions on this topic, and I looked them up - but because I'm still somewhat of a beginner, I can't really figure out the answer as it's too complex for me. So I wanted to give my own example, a dead simple one, and try to understand based on that.

Essentially what I want to do is run a function when an already existing variable, with a defined value, changes its value. Something like this:

var testVar = 5;
function letMeKnow() {
console.log("The variable has changed!);
}

What I want is, when I go to the console and type, say testVar = 7, I want the letMeKnow() function to run, and print something out in the console. More specifically, I want JavaScript to detect that the variable has changed, and run the function automatically. I know that this used to be possible with Object.observe() or Object.watch(), but since those are deprecated I suppose that I have to use getters and setters to achieve this. My question is, how would I do that for this example, keeping it as simple as possible?

Thanks!

dns_nx
  • 2,971
  • 3
  • 25
  • 52
Dzamija
  • 61
  • 1
  • 2
  • 1
    getter and setter is the way to do this – Krishjs Dec 19 '17 at 12:51
  • 2
    Write a function that sets the value for you and then use that everywhere. Other than objects with properties, timers that check values, or massive libraries you've not much other choice. There is no *"I've just changed"* event for variables. – Reinstate Monica Cellio Dec 19 '17 at 12:51
  • You should read to learn and understand. If it'd be "it's not working" question, then there could be a short, dead simple answer. Besides, you read in right direction (getters setters) so just keep it going! – entio Dec 19 '17 at 12:52
  • 1
    Possible duplicate of [Listening for variable changes in JavaScript](https://stackoverflow.com/questions/1759987/listening-for-variable-changes-in-javascript) – Jonathan Aug 19 '18 at 15:51

1 Answers1

6

A simple example using getter/setter can be like:

var obj = {
  value: '',
  letMeKnow() {
    console.log(`The variable has changed to ${this.testVar}`);
  },
  get testVar() {
    return this.value;
  },
  set testVar(value) {
    this.value = value;
    this.letMeKnow();
  }
}

console.log(obj.testVar)

obj.testVar = 5;
console.log(obj.testVar)

obj.testVar = 15;
console.log(obj.testVar)
palaѕн
  • 64,836
  • 15
  • 100
  • 121