admin管理员组

文章数量:1430715

Let's assume I have a variable:

var x = 0;

Each time this variable gets modified I want to run a function:

function(){
    console.log('x has been changed');
}

Would RxJs be appropiate for this task? If not, what other approach would work better?

Let's assume I have a variable:

var x = 0;

Each time this variable gets modified I want to run a function:

function(){
    console.log('x has been changed');
}

Would RxJs be appropiate for this task? If not, what other approach would work better?

Share Improve this question asked May 11, 2017 at 18:02 Andrei RosuAndrei Rosu 1,4152 gold badges13 silver badges29 bronze badges 1
  • 3 Make a function to vary that variable, instead of the other way around. function setX(newX) { window.x= newX} or something – TankorSmash Commented May 11, 2017 at 18:05
Add a ment  | 

4 Answers 4

Reset to default 2

You set value to property of an object, use set, get.

const x = {};

let value = 0;

function fn(oldValue, newValue) {
  console.log(`${oldValue} has been changed to ${newValue}`);
}

Object.defineProperty(x, "prop", {
  get() {
    return value
  },
  set(val) {
    fn(value, val);
    value = val;
  }
});

x.prop = 1;

x.prop = 10;

Douglas Tyler finished his answer before I had the chance to but yes, proxy is definitely something that you might use and here's an example :

const obj = {
    _id: null,
    set id(str) {
        console.log('setting the value !');
        this._id = str;
    },
    get id() {
        return this._id;
    }
}

I think a good bet would be to use Proxy, although this only works for objects, arrays and functions. Another option would be checking the value of on an interval and paring it to the old value of x which you've stored in another variable, though this may not work for your purposes. I think your best option would be to always set x with a function that does whatever other functionality you want it to.

You can use interval. Although I use Angular to $watch, you can see its implementation. There is also object.watch functionality but last i checked was not working in other browsers. So below is code using intervals (not a fun of intervals though)

var x=0, xWatcher = 0;
setInterval(function() {
   if ( x !== xWatcher ) {
      xWatcher = x;
      //Your code here
      xChanged()
   }
}, 50); // any delay you want 

function xChanged(){
   console.log('x has been changed');
}  

本文标签: javascriptRun Function on Variable ChangeStack Overflow