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?

2

2 Answers 2

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" 
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments