Created
November 4, 2016 15:31
-
-
Save nickbalestra/3212a6be18b1f0040d9bbaa7adf7731f to your computer and use it in GitHub Desktop.
MVI pattern using redux-like actions/reducer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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