Is there a way to call a callback when an object creates or modifies a key / value in JavaScript?

I am trying to figure out how to create an object in JavaScript that will trigger events when creating and changing arbitrary keys / values. Here are 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?

+3
source share
3 answers
 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" 
+2
source

You must define a getter and setter for the user. Thus, access to the properties of this object will lead to their elimination.

Check out the Mozilla documentation about them .

+1
source

All Articles