3

I am trying to figure out how to create an object in JavaScript that will trigger events on creation and change of arbitrary key/values. Here is some psuedocode:

var User = function () {
    var user = {};

    function keyAdded() { /* trigger an event */ }
    function keyChanged() { /* trigger an event */ }

    return user;
},
u = new User();

u.test = "testing"; // I want this to trigger an event (keyAdded)
u.test = "more testing"; // I want this to trigger another event (keyChanged)

I am stuck. Any ideas?

Roatin Marth
  • 21,331
  • 3
  • 46
  • 53
  • Someday browsers may support: http://stackoverflow.com/questions/1063813/listener-for-property-value-changes-in-a-javascript-object – epascarello Nov 09 '10 at 20:25
  • @epascarello, I think [ECMAScript Harmony Proxies](http://stackoverflow.com/questions/2266789/is-there-an-equivalent-of-the-nosuchmethod-feature-for-properties-or-a-way-t/3757676#3757676) will be implemented before `watch`, which isn't part of any *draft* standard. – Christian C. Salvadó Nov 09 '10 at 20:28

2 Answers2

2
function User() {
    this.assign = function(key, value) {
        if ( !this.hasOwnProperty(key) ) {
            this[key] = value;
            alert("key added");
        } else {
            this[key] = value;
            alert("key changed");
        }
    };
    return this;
}

u = new User();

u.assign("test", "testing"); // will alert "key added"
u.assign("test", "more testing"); // will alert "key changed"
Šime Vidas
  • 163,768
  • 59
  • 261
  • 366
1

You should define a getter and setter on User. That way, accessing properties on that object will fire those functions.

Check out the Mozilla documentation about them.

MartinodF
  • 7,737
  • 2
  • 29
  • 28