Skip to content

Instantly share code, notes, and snippets.

@iliyan-trifonov
Created October 15, 2017 16:50
Show Gist options
  • Save iliyan-trifonov/aba052f607b6031bf055a2dd7eac173a to your computer and use it in GitHub Desktop.
Save iliyan-trifonov/aba052f607b6031bf055a2dd7eac173a to your computer and use it in GitHub Desktop.
Cycle.js: text input, a button to click and Enter key press action

When the button is clicked or the Enter key is pressed while typing in the input, the text below is updated. The text below shows the text from the input as well as if the information is updated by pressing Enter or clicking on the button.

import {run} from '@cycle/run';
import {makeDOMDriver, div, button, br, input, span} from '@cycle/dom';
import xs from 'xstream';
import sampleCombine from 'xstream/extra/sampleCombine';
function main (sources) {
const click$ = sources.DOM.select('.button').events('click').startWith(false);
const input$ = sources.DOM.select('.input').events('input');
const enter$ = sources.DOM.select('.input').events('keyup').filter(ev => {
return ev.keyCode === 13;
});
const submit$ = xs.merge(click$, enter$);
const text$ = input$.map(ev => ev.target.value).startWith('');
const combined$ = submit$.compose(sampleCombine(text$));
const result$ = combined$.map(
([submit, text]) => {
return {enter: submit.keyCode && submit.keyCode === 13, txt: text};
});
return {
DOM: result$.map(result =>
div([
input('.input', {type: 'text'}),
button('.button', 'Click Me'),
br(), br(),
result ? 'Result: ' + result.txt : '',
br(),
span('Enter key pressed: ' + (result.enter ? 'YES' : 'NO'))
])
)
};
}
const drivers = {
DOM: makeDOMDriver('.app')
}
run(main, drivers);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment