How to trigger an event by monitoring a change in the value of a variable in node.js?

for example, get a var a = 123;

through websocket.

next time you get the data, a = 321,

how do I listen for changes in an and trigger an event when the value of a changes?

certainly do not want to use polling like setInterval to achieve.

Apr.20,2021

basic data types, if there is no similar api, object type, you can try setter/getter, your requirements here should be implemented through the Proxy object setter, is very convenient. For example:


function watchChange(object, onChange) {
  const handler = {
    defineProperty(target, property, descriptor) {
      onChange()
      return Reflect.defineProperty(target, property, descriptor)
    },
    deleteProperty(target, property) {
      onChange()
      return Reflect.deleteProperty(target, property)
    },
  }

  return new Proxy(object, handler)
}

const f = watchChange({}, () => {
  console.log('changed')
})

f.a = '1'
delete f.a

for demonstration purposes, I don't write the logic that provides handler.set, which is the proxy method when the value changes.


Mobx Ah

import {observable} from "mobx";

const value = observable.box("123");

console.log(value.get());
// prints '123'

value.observe(function(change) {
    console.log(change.oldValue, "->", change.newValue);
});

value.set("456");
Menu