Last active
January 3, 2019 22:45
-
-
Save jayrbolton/7e51080fccfcc3f0e4d4ec90447c9a25 to your computer and use it in GitHub Desktop.
counter list 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
const Component = require('..') | |
const h = require('../h') | |
// A single counter that can be incremented and decremented | |
const Counter = function (start) { | |
return Component('div', { | |
count: start, | |
add: ({ count }, n) => ({ count: count + n }), | |
view: ({ count, add }) => { | |
return h('div', [ | |
h('p', ['Count is ', count]), | |
h('button', { on: { click: () => add(1) } }, [ 'Increment' ]), | |
h('button', { on: { click: () => add(-1) } }, [ 'Decrement' ]) | |
]) | |
} | |
}) | |
} | |
// A counter list that uses the Counter component, initializing and removing counters dynamically. | |
const CounterList = function () { | |
return Component({ | |
counters: [], | |
total: 0, | |
countStart: 1, | |
add: ({ total }, n) => ({ total: total + n }), | |
append: ({ counters, countStart, total, add }) => { | |
const counter = Counter(countStart).on({ | |
add: (counter, n) => add(n) | |
}) | |
return { counters: counters.concat([ counter ]), total: total + countStart } | |
}, | |
remove: ({ counters }, id) => { | |
counters = counters.filter(c => c.id !== id) | |
const total = counters.reduce((sum, c) => sum + c.count, 0) | |
return { counters, total } | |
}, | |
setStart: (_, start) => ({ countStart: start }), | |
view: ({ total, countStart, counters, setStart, append, remove }) => { | |
return h('div', [ | |
h('p', [ 'Total count is ', total ]), | |
h('input', { | |
on: { input: ev => setStart(Number(ev.currentTarget.value)) }, | |
props: { | |
placeholder: 'Starting value', | |
type: 'number', | |
value: countStart | |
} | |
}), | |
h('button', { on: { click: () => append() } }, 'Add counter'), | |
h('div', counters.map(c => { | |
return h('div', { key: c.id }, [ | |
c.vnode, | |
h('button', { | |
on: { click: () => remove(c.id) } | |
}, 'Remove counter') | |
]) | |
})) | |
]) | |
} | |
}) | |
} | |
document.body.appendChild(CounterList().vnode.elm) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment