I need an event that runs when a variable changes

  • what event what variable? - Aliaksandr Pitkevich
  • there are no such events - Alexey Shimansky
  • If we are talking about simple variables declared anywhere in the code, then there is no standard way. However, you can think of your own version, or take an existing one, the benefit of which is enough to be searched for on request js event variable change . Here are the most interesting: ( stackoverflow.com/questions/40396558/… , ( stackoverflow.com/questions/10638769/… - Stanislav Belichenko
  • You can make a variable a property of an object, and use setter - Yaant

2 answers 2

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 .

  • 2
    this 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:

  1. Proxy object It allows you to intercept a call to another object. However, this method is implemented only in the specification of ES-2015.
  2. 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.
  3. There is a ready solution: FLOSS.js
  4. 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