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
4 Answers
Reset to default 2You 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
版权声明:本文标题:javascript - Run Function on Variable Change - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745488442a2660492.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论