const attachDebounce =
(target: EventTarget & HTMLInputElement,
eventAsString: string,
handleEmittedValue: (input: string) => any) => {
if (!target.hasAttribute('data-debounce-input-attached')) {
target.setAttribute('data-debounce-input-attached', '')
fromEvent(target, eventAsString)
.pipe(
map(e => (e.target as any).innerText),
debounceTime(500)
)
.subscribe(value => handleEmittedValue(value))
}
// (...)
onKeyDown: e => attachDebounce(e.currentTarget, 'keyup', (val) => console.log(val))
// (...)
- Leveraging TS, React, Redux, w/ Redux-Observables, the goal was to debounce input going into Redux store on an event (any event really) for dynamically created input elements. I choose
onKeyDown
(it just does nothing if the keyup
event is already attached).
- Wanted to avoid the
event.persist()
issue I was having using the non-reactive debounce implementation (underscore.js, lodash, etc.). See here.
- Already using RXJS, so no need to pull in another library
- Not happy about having to piggyback off another event (I wish RXJS has the ability to create Observables from an event object or something, or there was like an
onInit
event on dom objects)