Skip to content

Instantly share code, notes, and snippets.

@kurtlippert
Last active January 17, 2019 16:28
Show Gist options
  • Save kurtlippert/58658462d1cd3cc99c5835637fc82591 to your computer and use it in GitHub Desktop.
Save kurtlippert/58658462d1cd3cc99c5835637fc82591 to your computer and use it in GitHub Desktop.
Attach debounce event to target using rxjs
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))
    }

Usage

// (...)  
onKeyDown: e => attachDebounce(e.currentTarget, 'keyup', (val) => console.log(val))
// (...)

Why do?

  • 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment