Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function when a property gets set on an object

I don't really know how to explain this but I'll show you code and tell you what I'd like to achieve.

Let's say I make a quick object:

var test = {};

And then I set a property to it: (I insist on the syntax, it mustn't use any function as the setter)

test.hello = 'world';

Pretty simple, eh? Now I'd like to add a function to that object that would get called everytime a new property gets set. Like this:

var test = { 
                newPropertyHasBeenSet: function(name){ 
                    console.log(name + 'has been set.'); 
                } 
            };

test.hello = 'world';

// Now newPropertyHasBeenSet gets called with 'hello' as an argument.
// hello has been set.

I don't know if it's possible, but that would be quite amazing. Anyone has an idea of how to achieve so?

EDIT: I'd like also to be able to do the same for property get (so test.hello would call get('hello') for example).

EDIT2: This is for server-side javascript using node.js.

Thanks a lot and have a nice day!

like image 202
Tommy B. Avatar asked Jul 18 '12 23:07

Tommy B.


2 Answers

try this example in chrome (as mentioned in previous comments it uses ES6 Proxy):

var p = new Proxy(
    {},
    {
        get: function(obj, name) {
            console.log('read request to ' + name + ' property');
            if (name == 'test_test') return 1234;
            else return 'Meh';
        },
        set: function(obj, name, value) {
            console.log('write request to ' + name + ' property with ' + value + ' value');
        },
    }
);

console.log(p.test_test);
console.log(p.test);
p.qqq = 'test';

result:

read request to test_test property
1234
read request to test property
Meh
write request to qqq property with test value
like image 92
Andrey Sidorov Avatar answered Oct 31 '22 13:10

Andrey Sidorov


var test = {};

Object.defineProperty(test, "hello", {
    get : function () {
        return this._hello;
    },
    set : function (val) {
        alert(val);
        this._hello = val;
    }
});

test.hello = "world";

Something like that. But it will not work on old browsers.

You can find more options here: http://robertnyman.com/javascript/javascript-getters-setters.html

like image 31
Researcher Avatar answered Oct 31 '22 13:10

Researcher