Listening for variable changes in JavaScript

后端 未结 22 2816
自闭症患者
自闭症患者 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 + '<br />' + 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);
    <pre id="console">
    </pre>

    Other example

    // Console
    function print(t) {
      var c = document.getElementById('console');
      c.innerHTML = c.innerHTML + '<br />' + 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);
    <pre id="console">
    </pre>

    0 讨论(0)
  • 2020-11-21 07:07

    If you're using jQuery {UI} (which everyone should be using :-) ), you can use .change() with a hidden <input/> element.

    0 讨论(0)
  • 2020-11-21 07:08

    Sorry to bring up an old thread, but here is a little manual for those who (like me!) don't see how Eli Grey's example works:

    var test = new Object();
    test.watch("elem", function(prop,oldval,newval){
        //Your code
        return newval;
    });
    

    Hope this can help someone

    0 讨论(0)
  • 2020-11-21 07:09
    //ex:
    /*
    var x1 = {currentStatus:undefined};
    your need is x1.currentStatus value is change trigger event ?
    below the code is use try it.
    */
    function statusChange(){
        console.log("x1.currentStatus_value_is_changed"+x1.eventCurrentStatus);
    };
    
    var x1 = {
        eventCurrentStatus:undefined,
        get currentStatus(){
            return this.eventCurrentStatus;
        },
        set currentStatus(val){
            this.eventCurrentStatus=val;
          //your function();
        }
    };
    

    or

    /*  var x1 = {
    eventCurrentStatus:undefined,
    currentStatus : {
        get : function(){
            return Events.eventCurrentStatus
            },
        set : function(status){
            Events.eventCurrentStatus=status;
    
        },
    }*/
    console.log("eventCurrentStatus = "+ x1.eventCurrentStatus);
    x1.currentStatus="create"
    console.log("eventCurrentStatus = "+ x1.eventCurrentStatus);
    x1.currentStatus="edit"
    console.log("eventCurrentStatus = "+ x1.eventCurrentStatus);
    console.log("currentStatus = "+ x1.currentStatus);
    

    or

    /* global variable ku*/
        var jsVarEvents={};
        Object.defineProperty(window, "globalvar1", {//no i18n
            get: function() { return window.jsVarEvents.globalvarTemp},
            set: function(value) { window.window.jsVarEvents.globalvarTemp = value; }
        });
        console.log(globalvar1);
        globalvar1=1;
        console.log(globalvar1);
    
    0 讨论(0)
  • 2020-11-21 07:10

    AngularJS (I know this is not JQuery, but that might help. [Pure JS is good in theory only]):

    $scope.$watch('data', function(newValue) { ..
    

    where "data" is name of your variable in the scope.

    There is a link to doc.

    0 讨论(0)
  • 2020-11-21 07:10
    Utils = {
        eventRegister_globalVariable : function(variableName,handlers){
            eventRegister_JsonVariable(this,variableName,handlers);
        },
        eventRegister_jsonVariable : function(jsonObj,variableName,handlers){
            if(jsonObj.eventRegisteredVariable === undefined) {
                jsonObj.eventRegisteredVariable={};//this Object is used for trigger event in javascript variable value changes ku
            }
            Object.defineProperty(jsonObj, variableName , {
                        get: function() { 
                            return jsonObj.eventRegisteredVariable[variableName] },
                        set: function(value) {
                            jsonObj.eventRegisteredVariable[variableName] = value; handlers(jsonObj.eventRegisteredVariable[variableName]);}
                        });
                }
    
    0 讨论(0)
提交回复
热议问题