Track whether object changed

前端 未结 5 425
感情败类
感情败类 2021-01-12 23:33
// A simple Javascript Object / String
var object = \"hello\";

// Imagine a button in the DOM, and if it\'s clicked the object value will change
document.getElement         


        
相关标签:
5条回答
  • 2021-01-13 00:18

    You can track a JavaScript object by using Getters and Setters as described here,

    http://ejohn.org/blog/javascript-getters-and-setters/

    You can also look at,

    Javascript getters and setters for dummies?

    0 讨论(0)
  • 2021-01-13 00:24

    Javascript does not allow you to set programmatic watchpoints/events on arbitrary objects/variables.

    You can use encapsulation to hide individual values inside the object from the outside world, allowing them to be modified only through dedicated "setter" functions that have the side-effects you desire.

    0 讨论(0)
  • 2021-01-13 00:30

    Regardless of whatever framework you want to use, there is no magic to automatically triggering an event on property change. In your situation, what you should do is probably make an object surround this data and only expose get and set methods for it:

    var something = function()
    {
        var value = 10;
    
        this.getValue = function()
        {
            return value;
        }
    
        this.setValue = function(newValue)
        {
             ValueChanging(value, newValue);
             value = newValue;
        }
    
        var ValueChanging = function(old, new)
        {
             // Do Something
        }
    }
    
    0 讨论(0)
  • 2021-01-13 00:31

    Well you can make it an actual oject with get and set methods:

    // A simple Javascript Object 
    var object = new (function(){
        this.text = 'hello';
    
        this.setText = function(msg){
             this.text = msg
             //on change event
        }
    })();
    
    // Imagine a button in the DOM, and if it's clicked the object value will change
    document.getElementById("button").onclick = function(){
       object.setText('New Text');
    }
    

    Here is a demo fiddle: http://jsfiddle.net/maniator/BSYpz/

    0 讨论(0)
  • 2021-01-13 00:37

    Recent Google Chrome versions (ex. beta with "Enable Experimental JavaScript" flag on) support Object.observe() API. More info at RESPOND TO CHANGE WITH OBJECT.OBSERVE and working example

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