Note that there are some explanatory texts on larger screens.

plurals
  1. POMonitor All JavaScript Object Properties (magic getters and setters)
    primarykey
    data
    text
    <p>How do I emulate PHP-style __get() and __set() magic getter/setters in JavaScript? A lot of people say that this is currently impossible. I am almost certain that it is possible because projects like nowjs (<a href="http://nowjs.com" rel="nofollow noreferrer">http://nowjs.com</a>) do something like this.</p> <p>I know that you can utilize <a href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/get" rel="nofollow noreferrer">get</a> and <a href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/set" rel="nofollow noreferrer">set</a>, but these don't work when you're not sure what the property name will be. For example, <strong>what if you wanted an event handler to execute when a new property is created</strong>?</p> <p>Example of what I'd want to do:</p> <pre><code>var obj = {}; notify(obj, function(key, value) { //key is now the name of the property being set. //value is the value of the property about to be set console.log("setting " + key + " to " + value); }); obj.foo = 2; //prints "setting foo to 2" obj.bar = {a: 2}; //prints "setting bar to [Object]" //Notice that notify() worked even though 'foo' and 'bar' weren't even defined yet! </code></pre> <p>(The question is similar to the following questions:</p> <ul> <li><a href="https://stackoverflow.com/questions/6216553/is-there-a-way-to-monitor-changes-to-an-object">Is there a way to monitor changes to an object?</a></li> <li><a href="https://stackoverflow.com/questions/994143/JavaScript-getter-for-all-properties">JavaScript getter for all properties</a></li> </ul> <p>)</p> <p><strong>EDIT:</strong> It looks like this feature is called "dynamic proxies" and should appear in the ECMAScript "Harmony" standard (probably ES6). You can read more <a href="http://wiki.ecmascript.org/doku.php?id=harmony:proxies" rel="nofollow noreferrer">here</a>. A new 'Proxy' Object is introduced with a couple methods (I.e. Create() and createFunction() ).</p> <p>One could do this:</p> <pre><code>//Constructing an object proxy (proto is optional) var proxy = Proxy.create(handler, proto); proxy.foo = 2; //Triggers 'set' function in the handler (read about it) </code></pre> <p>Bottom line here: it doesn't work in most browsers, but an implementation is available for Node.js: <a href="https://github.com/samshull/node-proxy" rel="nofollow noreferrer">node-proxy</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload