I have written an answer where I had to write some decorators so I can hook into some function calls. However, I also want to hook into property setter calls as well but I'm not sure how that can be done.
In the answer, I wanted to hook into localStorage
so that I can listen in on any changes. I did this by decorating the setItem()
and removeItem()
functions.
I know I could decorate functions by creating new ones that at some point calls the original.
var _setItem = localStorage.setItem;
localStorage.setItem = function () {
_setItem.apply(this, arguments);
localStorageObserver.notifySubscribers(arguments[0]);
};
This works well but there are other uses I wish to hook into, property accesses. The following is all equivalent for Storage objects:
localStorage.setItem('someProperty', 'value');
localStorage.someProperty = 'value';
localStorage['someProperty'] = 'value';
So I would need to hook into the last two cases but I'm not sure how that can be accomplished.
How does one write a decorator for dynamic properties? Is it at all possible?
I suppose I could manually create properties as they are set to hide what is done by the storage object but that doesn't seem very scalable. If there was a simple setProperty(name, value)
function that I could hook into, I could decorate that. But as far as I know, that doesn't exist.