Skip to content

Instantly share code, notes, and snippets.

@jayrbolton
Last active September 13, 2016 09:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jayrbolton/c0024bb55bb80dc384431886b567fa67 to your computer and use it in GitHub Desktop.
Save jayrbolton/c0024bb55bb80dc384431886b567fa67 to your computer and use it in GitHub Desktop.
flyd + snabbdom component example (fahrenheit/celsius converter example)
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