Skip to content

Instantly share code, notes, and snippets.

@littlehaker
Created September 8, 2015 13:52
Show Gist options
  • Save littlehaker/bfb7281cc54e4765950f to your computer and use it in GitHub Desktop.
Save littlehaker/bfb7281cc54e4765950f to your computer and use it in GitHub Desktop.
FRP like Redux
var React = require('react');
var h = require('react-hyperscript');
var Bacon = require('baconjs');
// action
var action$ = new Bacon.Bus();
function filterAction(action_type) {
return function(action) {
return action.type === action_type;
};
}
var count$ = Bacon.update(
0,
[action$.filter(filterAction('inc'))], function(count, action) {
return count + action.payload.step;
},
[action$.filter(filterAction('dec'))], function(count, action) {
return count - action.payload.step;
}
);
// store
var state$ = Bacon.combineTemplate({
count: count$
}).log();
function dispatch(action_type, payload) {
action$.push({
type: action_type,
payload: payload
});
}
var App = React.createClass({
getInitialState: function() {
return {
count: 0
};
},
componentWillMount: function() {
state$.onValue(function(state) {
this.setState(state);
}.bind(this));
},
render: function() {
return h('div', [
h('span', 'Count: ' + this.state.count),
h('button', {onClick: dispatch.bind(null, 'inc', {step: 10})}, '+'),
h('button', {onClick: dispatch.bind(null, 'dec', {step: 1})}, '-'),
]);
}
});
React.render(h(App), document.getElementById('container'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment