Skip to content

Instantly share code, notes, and snippets.

@kaosat-dev
Last active February 18, 2017 15:27
Show Gist options
  • Save kaosat-dev/c812c4d1537f2910c3e3f1718cf9c17c to your computer and use it in GitHub Desktop.
Save kaosat-dev/c812c4d1537f2910c3e3f1718cf9c17c to your computer and use it in GitHub Desktop.
Cycle.js Onionify issue
import { run } from '@cycle/xstream-run';
import { button, div,
makeDOMDriver } from '@cycle/dom';
import xs from 'xstream';
import isolate from '@cycle/isolate';
import onionify from 'cycle-onionify';
import R from 'ramda';
import {pick, mix} from 'cycle-onionify'
//simple helper for more terse syntax
function domEvent(sources, selector, event){
return sources.DOM.select(selector).events(event)
}
//another helper : only for BASIC state/ reducer$
function makeStateAndReducers$ (actions$, actionFns, sources) {
const {init} = actionFns
const init$ = xs.of(init)
const elements = Object.keys(actions$).map(function (actionName$) {
const name = actionName$.replace('Action$', '')
const actFn = actionFns[name]
const act$ = actions$[actionName$].mapTo(actFn)
return act$
})
const reducer$ = xs.merge(init$, ...elements)
const state$ = sources.onion.state$
return {state$, reducer$}
}
function Counter(sources, isolateId='') {
const init = () => ({ count: 0, toggled: true })
const inc = state => ({...state, count: state.count + 1 })
const dec = state => ({...state, count: state.count - 1 })
const toggle = state => ({...state, toggled: !state.toggled })
const view = state => div([
div(state.count.toString()),
div('Toggled: '+state.toggled),
button('.toggle'+isolateId,'toggle'),
state.toggled ? div('.toggleable', [
button('.inc'+isolateId, '+'),
button('.dec'+isolateId, '-')
]) : null
])
const _domEvent = domEvent.bind(null, sources)
const incAction$ = _domEvent('.inc'+isolateId, 'click')
const decAction$ = _domEvent('.dec'+isolateId, 'click')
const toggleAction$ = _domEvent('.toggle'+isolateId, 'click')
const {state$, reducer$} = makeStateAndReducers$({incAction$, decAction$, toggleAction$}, {init, inc, dec, toggle}, sources)
return {
DOM: state$.map(view),
onion: reducer$
}
}
function main(sources){
const init = () => ({})
const counter1 = isolate(Counter, 0)(sources)
const counter2 = isolate(Counter, 1)(sources)
const reducer$ = xs.merge(xs.of(init), counter1.onion, counter1.onion)
const state$ = sources.onion.state$
const vdom$ = xs.combine(state$, counter1.DOM, counter2.DOM)
.map(([ state, counter1, counter2 ]) => div([
counter1,
counter2,
div(JSON.stringify(state, null, 4)),
div('oh yeah'),
]))
return {
DOM: vdom$,
onion: reducer$
}
}
const wrappedMain = onionify(main)
run(wrappedMain, {
DOM: makeDOMDriver('#app')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment