Listening for variable changes in JavaScript

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

提交回复
热议问题