Adam Halasz
Adam Halasz

Reputation: 58301

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.

Upvotes: 6

Views: 6261

Answers (5)

Tihauan
Tihauan

Reputation: 2780

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

Upvotes: 3

Naftali
Naftali

Reputation: 146302

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/

Upvotes: 5

Tejs
Tejs

Reputation: 41236

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

Upvotes: 3

Aravindan R
Aravindan R

Reputation: 3084

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?

Upvotes: 4

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385104

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.

Upvotes: 6

Related Questions