Skip to content

Instantly share code, notes, and snippets.

@nickbalestra
Created November 4, 2016 15:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickbalestra/3212a6be18b1f0040d9bbaa7adf7731f to your computer and use it in GitHub Desktop.
Save nickbalestra/3212a6be18b1f0040d9bbaa7adf7731f to your computer and use it in GitHub Desktop.
MVI pattern using redux-like actions/reducer
import xs from 'xstream';
import {div, button} from '@cycle/dom'
function view(state$) {
const vtree$ = state$.map( state =>
div([
button('.increase', 'Moar'),
button('.decrease', 'Less'),
div(`Count: ${state.count}`)
])
)
return vtree$
}
function intent(interaction$) {
const increase$ = interaction$
.select('.increase')
.events('click')
.mapTo({type: 'INCREASE'})
const decrease$ = interaction$
.select('.decrease')
.events('click')
.mapTo({type: 'DECREASE'})
const action$ = xs.merge(increase$, decrease$)
return action$
}
function model(action$) {
const reducer = (state, action) => {
switch(action.type) {
case 'INCREASE':
return Object.assign({}, state, {
count: state.count + 1
})
case 'DECREASE':
return Object.assign({}, state, {
count: state.count - 1
})
}
}
const state$ = action$.fold(reducer, {count: 0})
return state$
}
export default function dialogue (sources) {
return {
DOM: view(model(intent(sources.DOM)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment