I need an event that runs when a variable changes
2 answers
To create an event when the value of a variable changes, the FLOSS.js library is great (less than 1kb).
Create variable:
FLOSS({ name: 'userName', value: 'Petr Soskov', action: function(value){ alert(value) }, defer: true /* отменяю вызов action при создании переменной */ }); console.log(userName); /* Petr Soskov */ userName = 'Ivan Ivanov'; /* alert('Ivan Ivanov'); */
At change userName
will fulfill action
.
Link to the library .
- 2this thing produces a bunch of global variables, which is not very cool and if you declare two with the same
name
, then there will be problems - ThisMan
|
You can use the following solutions to track changes:
- Proxy object It allows you to intercept a call to another object. However, this method is implemented only in the specification of ES-2015.
- You can also try using Object.defineProperty. As with the proxy - all this work with the properties of objects. You must be careful not to cause endless recursion.
- There is a ready solution: FLOSS.js
- And finally, it is possible to implement a narrowly focused functional to solve the problem:
var name = 'Boris'; let changeName = newName => { name = newName; console.log('New name: ' + name); } changeName('Petr');
- Yes, I asked this question a long time ago. Now I realized that there are getters and setters. - ishidex2
|
js event variable change
. Here are the most interesting: ( stackoverflow.com/questions/40396558/… , ( stackoverflow.com/questions/10638769/… - Stanislav Belichenko