How to extend native events
I have a CurrencyManager which handles when the user inputs a number and converts it to a currency in a input field and manages the cursor position. I'd like to add the unmasked and masked value from the manager to all of the events on the input field so end users have access to it. Maybe I'm overthinking the approach but right now I have a curried wrapper function that takes a function and returns a function that receives its native event and calls the original function with the data added to it.
This all works, but it's making forwarding the ref to higher level components for them to manage the value nearly impossible.
It's also annoying to have to do this for the 10+ types of input event handlers.
Is there a cleaner way to implement this?
Maybe having the currency manager intercept the input element's prototype with a proxy so I could do something like
e.currentTarget.unmaskedValue
and inputRef.disconnect()
but I'm not sure how to do that and I know that's usually discouraged because of unexpected behavior/compatibility issues.1 Reply
This would probably be a good place for a Proxy https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy.
I mean, not necessarily in the input itself but you could create a proxy for the currency and you can do whatever you need on
set()
and on get()
, which is where you could provide your masked
and unmasked
valuesProxy - JavaScript | MDN
The Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object.