1

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

Lupor
  • 59
  • 8
  • use setter https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Functions/set – heleg Feb 29 '20 at 18:29

1 Answers1

2

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)
Addis
  • 2,480
  • 2
  • 13
  • 21
  • 1
    Thanks! works like a charm! though, do you happen to know if there is an polyfill for proxies? as it seems to not support IE ^^ (from https://caniuse.com/#search=Proxy) – Lupor Mar 01 '20 at 12:08
  • 1
    checkout https://stackoverflow.com/questions/45285992/es6-proxy-polyfill-for-ie11 – Addis Mar 01 '20 at 13:23