Listening for variable changes in JavaScript

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

    It's not directly possible.

    However, this can be done using CustomEvent: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent

    The below method accepts an array of variable names as an input and adds event listener for each variable and triggers the event for any changes to the value of the variables.

    The Method uses polling to detect the change in the value. You can increase the value for timeout in milliseconds.

    function watchVariable(varsToWatch) {
        let timeout = 1000;
        let localCopyForVars = {};
        let pollForChange = function () {
            for (let varToWatch of varsToWatch) {
                if (localCopyForVars[varToWatch] !== window[varToWatch]) {
                    let event = new CustomEvent('onVar_' + varToWatch + 'Change', {
                        detail: {
                            name: varToWatch,
                            oldValue: localCopyForVars[varToWatch],
                            newValue: window[varToWatch]
                        }
                    });
                    document.dispatchEvent(event);
                    localCopyForVars[varToWatch] = window[varToWatch];
                }
            }
            setTimeout(pollForChange, timeout);
        };
        let respondToNewValue = function (varData) {
            console.log("The value of the variable " + varData.name + " has been Changed from " + varData.oldValue + " to " + varData.newValue + "!!!"); 
        }
        for (let varToWatch of varsToWatch) {
            localCopyForVars[varToWatch] = window[varToWatch];
            document.addEventListener('onVar_' + varToWatch + 'Change', function (e) {
                respondToNewValue(e.detail);
            });
        }
        setTimeout(pollForChange, timeout);
    }
    

    By calling the Method:

    watchVariables(['username', 'userid']);
    

    It will detect the changes to variables username and userid.

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

    This is an old thread but I stumbled onto second highest answer (custom listeners) while looking for a solution using Angular. While the solution works, angular has a better built in way to resolve this using @Output and event emitters. Going off of the example in custom listener answer:

    ChildComponent.html

    <button (click)="increment(1)">Increment</button>
    

    ChildComponent.ts

    import {EventEmitter, Output } from '@angular/core';
    
    @Output() myEmitter: EventEmitter<number> = new EventEmitter<number>();
    
    private myValue: number = 0;
    
    public increment(n: number){
      this.myValue += n;
    
      // Send a change event to the emitter
      this.myEmitter.emit(this.myValue);
    }
    

    ParentComponent.html

    <child-component (myEmitter)="monitorChanges($event)"></child-component>
    <br/>
    <label>{{n}}</label>
    

    ParentComponent.ts

    public n: number = 0;
    
    public monitorChanges(n: number){
      this.n = n;
      console.log(n);
    }
    

    This will now update non parent each time the child button is clicked. Working stackblitz

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

    As Luke Schafer's answer (note: this refers to his original post; but the whole point here remains valid after the edit), I would also suggest a pair of Get/Set methods to access your value.

    However I would suggest some modifications (and that's why I'm posting...).

    A problem with that code is that the field a of the object myobj is directly accessible, so it's possible to access it / change its value without triggering the listeners:

    var myobj = { a : 5, get_a : function() { return this.a;}, set_a : function(val) { this.a = val; }}
    /* add listeners ... */
    myobj.a = 10; // no listeners called!
    

    Encapsulation

    So, to guarantee that the listeners are actually called, we would have to prohibit that direct access to the field a. How to do so? Use a closure!

    var myobj = (function() { // Anonymous function to create scope.
    
        var a = 5;            // 'a' is local to this function
                              // and cannot be directly accessed from outside
                              // this anonymous function's scope
    
        return {
            get_a : function() { return a; },   // These functions are closures:
            set_a : function(val) { a = val; }  // they keep reference to
                                                // something ('a') that was on scope
                                                // where they were defined
        };
    })();
    

    Now you can use the same method to create and add the listeners as Luke proposed, but you can rest assured that there's no possible way to read from or write to a going unnoticed!

    Adding encapsulated fields programmatically

    Still on Luke's track, I propose now a simple way to add encapsulated fields and the respective getters/setters to objects by the means of a simple function call.

    Note that this will only work properly with value types. For this to work with reference types, some kind of deep copy would have to be implemented (see this one, for instance).

    function addProperty(obj, name, initial) {
        var field = initial;
        obj["get_" + name] = function() { return field; }
        obj["set_" + name] = function(val) { field = val; }
    }
    

    This works the same as before: we create a local variable on a function, and then we create a closure.

    How to use it? Simple:

    var myobj = {};
    addProperty(myobj, "total", 0);
    window.alert(myobj.get_total() == 0);
    myobj.set_total(10);
    window.alert(myobj.get_total() == 10);
    
    0 讨论(0)
  • 2020-11-21 07:25

    In my case, I was trying to find out if any library I was including in my project was redefining my window.player. So, at the begining of my code, I just did:

    Object.defineProperty(window, 'player', {
      get: () => this._player,
      set: v => {
        console.log('window.player has been redefined!');
        this._player = v;
      }
    });
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-21 07:26

    Recently found myself with the same issue. Wanted to listen for on change of a variable and do some stuff when the variable changed.

    Someone suggested a simple solution of setting the value using a setter.

    Declaring a simple object that keeps the value of my variable here:

    var variableObject = {
        value: false,
        set: function (value) {
            this.value = value;
            this.getOnChange();
        }
    }
    

    The object contains a set method via which I can change the value. But it also calls a getOnChange() method in there. Will define it now.

    variableObject.getOnChange = function() {
        if(this.value) {
            // do some stuff
        }
    }
    

    Now whenever I do variableObject.set(true), the getOnChange method fires, and if the value was set as desired (in my case: true), the if block also executes.

    This is the simplest way I found to do this stuff.

    0 讨论(0)
提交回复
热议问题