Listening for variable changes in JavaScript

后端 未结 22 2852
自闭症患者
自闭症患者 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:26

    No.

    But, if it's really that important, you have 2 options (first is tested, second isn't):

    First, use setters and getters, like so:

    var myobj = {a : 1};
    
    function create_gets_sets(obj) { // make this a framework/global function
        var proxy = {}
        for ( var i in obj ) {
            if (obj.hasOwnProperty(i)) {
                var k = i;
                proxy["set_"+i] = function (val) { this[k] = val; };
                proxy["get_"+i] = function ()    { return this[k]; };
            }
        }
        for (var i in proxy) {
            if (proxy.hasOwnProperty(i)) {
                obj[i] = proxy[i];
            }
        }
    }
    
    create_gets_sets(myobj);
    

    then you can do something like:

    function listen_to(obj, prop, handler) {
        var current_setter = obj["set_" + prop];
        var old_val = obj["get_" + prop]();
        obj["set_" + prop] = function(val) { current_setter.apply(obj, [old_val, val]); handler(val));
    }
    

    then set the listener like:

    listen_to(myobj, "a", function(oldval, newval) {
        alert("old : " + oldval + " new : " + newval);
    }
    

    Second, you could put a watch on the value:

    Given myobj above, with 'a' on it:

    function watch(obj, prop, handler) { // make this a framework/global function
        var currval = obj[prop];
        function callback() {
            if (obj[prop] != currval) {
                var temp = currval;
                currval = obj[prop];
                handler(temp, currval);
            }
        }
        return callback;
    }
    
    var myhandler = function (oldval, newval) {
        //do something
    };
    
    var intervalH = setInterval(watch(myobj, "a", myhandler), 100);
    
    myobj.set_a(2);
    

提交回复
热议问题