6

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!

4
  • 1
    getter and setter is the way to do this Commented Dec 19, 2017 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. Commented Dec 19, 2017 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! Commented Dec 19, 2017 at 12:52
  • 1
    Possible duplicate of Listening for variable changes in JavaScript Commented Aug 19, 2018 at 15:51

1 Answer 1

12

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.