Skip to content

Instantly share code, notes, and snippets.

@indigo0086
Last active March 16, 2016 18:56
Show Gist options
  • Save indigo0086/5e67663405c4d6642c29 to your computer and use it in GitHub Desktop.
Save indigo0086/5e67663405c4d6642c29 to your computer and use it in GitHub Desktop.
Kefir Recipes
'use strict';
// This allows you to filter every other click event (first one included)
// By making the initial value an object, eliminates type checking
// click markedClicks:--------<value: true>--<value: false>---------<value: true>---...etc
// oddClicks: --------<value: true>-------------------------<value: true>---...etc
// evenClicks: -----------------------<value: false>-------------------------...etc
const markedClicks = Kefir.fromEvents(document.body, 'click')
.scan((prev, next) => !prev, false) //This can be an object with a shouldFire property if you need to map anything else
.skip(1); //This will skip the currentValue called immediately due to the seed
const evenClicks = markedClicks.filter().log();
const oddClicks = markedClicks.filter(x => !x).log();
//Passing previous value through to another event
//Thanks to @rpominov https://github.com/rpominov/kefir/issues/189#issuecomment-193851575
//dragStart: --{dragged, true}---------------------------
//dragEnd: -----------------------------{false}--------
//dragValues --{dragged, true}------------{dragged, false}
const draggableElements = document.querySelectorAll('.drag-elem');
const dragStart = Kefir.fromEvents(draggableElements, 'dragstart')
.map((evt) => ({ dragged: evt.target, value: true }));
const dragEnd = Kefir.fromEvents(draggableElements, 'dragend')
.map((evt) => ({ value: false }));
const dragValues = dragStart.flatMap((start) => {
return Kefir.merge([
Kefir.constant(start), //will be emitted immediately on click
dragEnd.map((value) => ({ target: start.target, value})) //will return to its value
])
});
dragValues.log();
// Observe a keyup event while typing and after typing has finished
// Good for monitoring any
var keyUp = Kefir.fromEvents(document.body, 'keyup');
Kefir.merge([
keyUp.map(x => true),
keyUp.debounce(1000).map(x => false)
]).onValue(isTyping => {
if(isTyping) { /*...*/ }
else { /*..*/ }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment