Skip to content

Instantly share code, notes, and snippets.

@franciscotln
Created October 19, 2016 00:26
Show Gist options
  • Save franciscotln/e1d9b270ca1051fece868738d854d4e9 to your computer and use it in GitHub Desktop.
Save franciscotln/e1d9b270ca1051fece868738d854d4e9 to your computer and use it in GitHub Desktop.
using cyclejs
'use strict';
import { run } from '@cycle/rxjs-run';
import { makeDOMDriver, div, input, p, li, ul, span, h2, h5, label, hr } from '@cycle/dom';
import { makeHTTPDriver } from '@cycle/http';
import { Observable } from 'rxjs';
import isolate from '@cycle/isolate';
function intent(DOMSource) {
return DOMSource.select('.checkbox').events('click')
.map(ev => ev.target.checked);
}
function model(newVal$, props$) {
const initialValue$ = props$.map(props => props.checked).first();
const value$ = initialValue$.concat(newVal$);
const state$ = value$.combineLatest(props$, (value, props) => ({
label: props.label,
checked: value
}));
return state$;
}
function view(state$) {
return state$.map(state =>
div('.checkbox-container', [
label('.checkbox-label', state.label),
input('.checkbox', { attrs: { type: 'checkbox', checked: state.checked } })
])
);
}
function Checkbox(sources) {
const change$ = intent(sources.DOM);
const state$ = model(change$, sources.props);
const vtree$ = view(state$);
return { DOM: vtree$, state$ };
}
const IsolatedCheckbox = sources => isolate(Checkbox)(sources)
function main(sources) {
const props = [
{ label: 'Wine', checked: false },
{ label: 'Water', checked: true },
{ label: 'Beer', checked: false }
];
const checkboxesSinks = props.map(prop =>
IsolatedCheckbox({
DOM: sources.DOM,
props: Observable.of(prop)
})
);
const checkboxesVTrees$ = checkboxesSinks.map(sink => sink.DOM)
const checkboxesStates$ = checkboxesSinks.map(sink => sink.state$);
const states$ = Observable.combineLatest(...checkboxesStates$, (state1, state2, state3) =>
[ state1, state2, state3 ]
);
const vtree$ = Observable.combineLatest(...checkboxesVTrees$, states$,
(Checkbox1, Checkbox2, Checkbox3, states) =>
div('.checkboxes-wrapper', [
h5('Multiple checkboxes:'),
Checkbox1,
Checkbox2,
Checkbox3,
hr(),
p(`Current state: ${JSON.stringify(states)}`)
])
);
return { DOM: vtree$ };
}
const driver = {
DOM: makeDOMDriver('body'),
}
run(main, driver);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment