简体   繁体   中英

Creating an Event Listener which listens whether a value in a variable has changed

I was wondering if there are any modern methods for JavaScript (or maybe using jQuery) to create an event listener which fires a function or a piece of code whenever a variable's value has changed?

var test = 1;

I want to have an event listener fire whenever the variable test is any other value but 1 .

You can use an object with a setter :

 const obj = { _test: 1, set test(t) { t !== 1 && console.log(t); // fire the function return _test = t; } } obj.test = 5; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM