Reputation: 59
Imagine the following....
function MyFunctional()
{
this._internal = "";
}
var foo = new MyFunctional();
foo.bar = 0;
foo.gent = "foobar";
how is it possible to fire an event whenever I call foo.x = y;
or foo['x'] = y;
? would it be to create a setTimeout and check against the last array of property names? that would seem kinda expensive ^^
Thanks for reading, hopeful for an answer :D
Upvotes: 1
Views: 184
Reputation: 2530
You can do it with proxy
object which defines custom behavior for fundamental operations
function MyFunctional() {
this._internal = "";
}
var foo = new MyFunctional();
//define the object whose properties are functions that define the behavior
//of the proxy when an operation is performed on it.
const handler = {
set: function(obj, prop, value) {
if(!(prop in obj)) {
alert(`property '${prop}' added`);
}
obj[prop] = value;
}
}
const p = new Proxy(foo, handler);
p.bar = 0;
p.gent = "foobar";
p.bar = 2;
console.log(foo)
Upvotes: 2