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

1

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

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 caniuse.com/#search=Proxy)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.