Skip to content

Instantly share code, notes, and snippets.

@mauriciosoares
Created October 19, 2015 20:07
Show Gist options
  • Save mauriciosoares/5f7d185e900a23895e24 to your computer and use it in GitHub Desktop.
Save mauriciosoares/5f7d185e900a23895e24 to your computer and use it in GitHub Desktop.
rxjs double click example
let clickStream = Rx.Observable.fromEvent(document.getElementById('link'), 'click');
clickStream
.buffer(clickStream.debounce(250))
.map(list => list.length)
.filter(x => x === 2)
.subscribe(() => {
console.log('doubleclick');
})
@riskers
Copy link

riskers commented Jan 25, 2019

rx6

import { fromEvent,  } from 'rxjs'; 
import { map, buffer, debounceTime } from 'rxjs/operators';

const mouse$ = fromEvent(document, 'click')

const buff$ = mouse$.pipe(
  debounceTime(250),
)

const click$ = mouse$.pipe(
  buffer(buff$),
  map(list => {
    return list.length;
  }),
  filter(x => x === 2),
)

click$.subscribe(() => {
  console.log('doubleclick')
})

@elonmallin
Copy link

Will fire directly after x clicks instead of waiting for the time to run out. Useful for more clicks and longer timespans.

import { fromEvent,  } from 'rxjs'; 
import { map, bufferCount, filter } from 'rxjs/operators';

const clickCount = 5;
const clickTimespan = 2000;

fromEvent(document, 'click').pipe(
  map(() => new Date().getTime()),
  // Emit the last `clickCount` timestamps.
  bufferCount(clickCount, 1),
  // `timestamps` is an array the length of `clickCount` containing the last added `timestamps`.
  filter((timestamps) => {
    // `timestamps[0]` contains the timestamp `clickCount` clicks ago.
    // Check if `timestamp[0]` was within the `clickTimespan`.
    return timestamps[0] > new Date().getTime() - clickTimespan;
  })
)
  // Will emit after `clickCount` clicks if the first one happened within the `clickTimespan`.
  // Won't wait until `clickTimespan` runs out to emit.
  .subscribe(() => {
    console.log(`${clickCount} clicks happened within the timespan of ${clickTimespan} ms`);
  })

@EmanH
Copy link

EmanH commented Nov 3, 2021

This is simpler imho. Will also fire directly directly after x. Only works for double-clicking (not triple click, etc.)

const doubleClickTimespan = 300
Rx.Observable.fromEvent(document.getElementById('link'), 'click')
.pipe(
  startWith(null), pairwise(),
  takeWhile(e => !e[0] || e[0].target === e[1]?.target),
  filter(e => e[0] !== null && e[1].timeStamp - e[0].timeStamp <= doubleClickTimespan),
  map(e => e[0]),
  take(1), repeat()
).subscribe(e => {
  console.log('double clicked', e);
}))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment