Listening for variable changes in JavaScript

后端 未结 22 2792
自闭症患者
自闭症患者 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: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]);}
                        });
                }
    

提交回复
热议问题