Skip to content

Instantly share code, notes, and snippets.

@ebidel
Created September 12, 2015 17:01
Show Gist options
  • Save ebidel/d48d590ff54a6e3370ee to your computer and use it in GitHub Desktop.
Save ebidel/d48d590ff54a6e3370ee to your computer and use it in GitHub Desktop.
DOM property watcher using ES6 proxies.
// Watch accesses/sets on a DOM element property.
function watchPropsOn(el) {
return new Proxy(el, {
get(target, propKey, receiver) {
//return Reflect.get(target, propKey, receiver);
console.log('get', propKey);
return el[propKey];
},
set(target, propKey, value, receiver) {
console.log('set', propKey, value);
target[propKey] = value;
}
});
}
let el = document.createElement('div');
let elProxy = watchPropsOn(el);
elProxy.textContent = 'hi there';
console.log(elProxy.textContent);
@pwFoo
Copy link

pwFoo commented Feb 26, 2022

function can watch properties, but ignores setAttribute() to change attributes / properties and fails with method calls!
Error message for "setAttribute" call:

get setAttribute
VM20409:1 Uncaught TypeError: Illegal invocation
    at <anonymous>:1:7

Could be handled by get handler like that.

function watchPropsOn(el) {
                return new Proxy(el, {
                    get(target, propKey, receiver) {
                    console.log('get', propKey);
                    return el[propKey].call ? (...args) => el[propKey](...args) : el[propKey];  // proxy methods if callable, else return property
                    },
                    set(target, propKey, value, receiver) {
                    console.log('set', propKey, value);
                    target[propKey] = value;
                    }
                });
            }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment