开发者

Track whether object changed

// 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.getElementById("button").onclick = function(){
   window.object = "hello world";
}

// Now I would like to track and do something when the object is changed, ex:
object.onreadystatechange = function(){
   alert(object);
}

Note: This could sound stupid, because I could get the change in the onclick event on the button, but this is not what I want, I want strictly to track the change on the object itself for开发者_运维问答 any kind of use, the above code is is just an example.


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.


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/


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?


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
    }
}


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜