I'd like to subscribe for all changes of value property in all inputs using custom setter:
Object.defineProperty(HTMLInputElement.prototype, 'value', {
set: function(newValue) {
// do some logic here
// WHAT PUT HERE to call "super setter"?
}
});
If I use this.value = newValue; I'm getting Maximum call stack size exceeded which is quite right but...
Nevermind. What should I call to change value in correct way? Here is
JSFIDDLE with more detailed explanation.
Yes, this can be achieved using JavaScript:
(function (realHTMLInputElement) {
Object.defineProperty(HTMLInputElement.prototype, 'value', {
set: function (value) {
// Do some logic here
return realHTMLInputElement.set.call(this, value);
},
});
}(Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')));
We use a IIFE to pass in the original definition for value and then call the original set function from within our new definition.
If you combine that with a capture input event handler on document,¹ you get notified of all changes, whether via code (through the above) or by the user.
function yourCustomLogic(input, value) {
console.log(`${input.id ? "Input #" + input.id : "An input"} set to "${value}"`);
}
// Catch programmatic changes
(function (realHTMLInputElement) {
Object.defineProperty(HTMLInputElement.prototype, "value", {
set: function (value) {
// Do some logic here
yourCustomLogic(this, value);
return realHTMLInputElement.set.call(this, value);
},
});
})(Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value"));
// Catch end-user changes
document.addEventListener(
"input",
(event) => {
if (event.target.tagName === "INPUT") {
yourCustomLogic(event.target, event.target.value);
}
},
true // Capture handler
);
document.getElementById("example").value = "Updated by code.";
<input type="text" id="example">
The reason for using a capture phase handler (rather than bubbling phase) is twofold:
Officially, input doesn't bubble, although most (all?) current browsers bubble it despite what the spec says
It prevents event handlers that stop propagation from stopping the event before it gets to document
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With