Last active
September 13, 2016 09:49
-
-
Save jayrbolton/c0024bb55bb80dc384431886b567fa67 to your computer and use it in GitHub Desktop.
flyd + snabbdom component example (fahrenheit/celsius converter example)
This file contains hidden or 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 flyd from 'flyd' | |
import h from 'snabbdom/h' | |
import snabbdom from 'snabbdom' | |
import render from 'ff-core/render' | |
// Initialize the state object | |
const init = ()=> { | |
// Initialize input change event streams | |
// Think of streams as values that change over time. | |
// These two streams are input values that change over time, but start empty. | |
const changeCelsius$ = flyd.stream() | |
const changeFahren$ = flyd.stream() | |
// Compute temperature values based on input changes | |
const fahren$ = flyd.map(c => c * 9/5 + 32, state.changeCelsius$) | |
const celsius$ = flyd.map(f => f * 1.8 + 32, state.changeFahren$) | |
// The init function returns the state object for use in the view. | |
return {changeCelsius$, changeFahren$, fahren$, celsius$} | |
} | |
// The view takes the state object, initialized with init() | |
// It returns a Snabbdom tree | |
const view = state => { | |
return h('body', [ | |
h('div', [ | |
h('label', 'Fahrenheit') | |
, h('input', { | |
// Call the stream to obtain its current value. | |
props: {value: state.fahren$()} | |
// Use the stream as an event handler. | |
, on: {keyup: ev => state.changeFahren$(ev.currentTarget.value)} | |
}) | |
]) | |
, h('div', [ | |
h('label', 'Celsius') | |
, h('input', { | |
props: {value: state.celsius$()} | |
, on: {keyup: ev => state.changeCelsius$(ev.currentTarget.value)} | |
}) | |
]) | |
]) | |
} | |
// Render the above component to the page | |
// Init the Snabbdom patch function. | |
// You can pick snabbdom modules here. | |
const patch = snabbdom.init([ | |
require('snabbdom/modules/eventlisteners') | |
, require('snabbdom/modules/props') | |
]) | |
// Call the ff-core/render function to render the component to the dom. | |
// We only need to call this render function once | |
// for the top level component. | |
// The dom will automatically patch when streams change. | |
render({container: document.body, state: init(), patch, view}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment