Lupor
Lupor

Reputation: 59

JavaScript detect when new object property is created

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

Answers (1)

Addis
Addis

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

Related Questions