Listening for variable changes in JavaScript

后端 未结 22 2794
自闭症患者
自闭症患者 2020-11-21 06:57

Is it possible to have an event in JS that fires when the value of a certain variable changes? JQuery is accepted.

22条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 07:06

    Using Prototype: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

    // Console
    function print(t) {
      var c = document.getElementById('console');
      c.innerHTML = c.innerHTML + '
    ' + t; } // Demo var myVar = 123; Object.defineProperty(this, 'varWatch', { get: function () { return myVar; }, set: function (v) { myVar = v; print('Value changed! New value: ' + v); } }); print(varWatch); varWatch = 456; print(varWatch);

    Other example

    // Console
    function print(t) {
      var c = document.getElementById('console');
      c.innerHTML = c.innerHTML + '
    ' + t; } // Demo var varw = (function (context) { return function (varName, varValue) { var value = varValue; Object.defineProperty(context, varName, { get: function () { return value; }, set: function (v) { value = v; print('Value changed! New value: ' + value); } }); }; })(window); varw('varWatch'); // Declare print(varWatch); varWatch = 456; print(varWatch); print('---'); varw('otherVarWatch', 123); // Declare with initial value print(otherVarWatch); otherVarWatch = 789; print(otherVarWatch);

提交回复
热议问题