@erickmerchant/framework
This scoped package is my personal framework. I use it on a number of small projects.
An Example
This example uses yo-yo (which uses hyperx), but you should be able to use diffHTML and possibly other solutions.
const framework = require('@erickmerchant/framework')
const html = require('yo-yo')
const diff = html.update
const target = document.querySelector('main')
framework({target, store, component, diff})()
function store (seed) {
seed(0)
return function (commit, action) {
switch (action) {
case 'increment': commit((state) => state + 1)
case 'decrement': commit((state) => state - 1)
}
}
}
function component ({state, dispatch}) {
return html`<main>
<output>${state}</output>
<br>
<button onclick=${decrement}>--</button>
<button onclick=${increment}>++</button>
</main>`
function decrement () {
dispatch('decrement')
}
function increment () {
dispatch('increment')
}
}
API Reference
Framework Code
framework
framework({target, store, component, diff, raf})
The function exported by this module.
- target: a DOM element. The place to render your application
- store
- component
- diff
- raf: optional. A replacement for window.requestAnimationFrame. It defaults to window.requestAnimationFrame
Returns a function. See init
state
This is what is initially passed to seed and subsequently returned from commit callbacks. It can be anything from simply a number like in the example, to a complex object.
seed
seed(state)
It should be passed the initial state
commit
commit((current) => next)
It's passed a callback that receives the current state and should return the new state.
dispatch
dispatch(...arguments)
Initializes a change in state and causes a render
- arguments: all get passed to the agent
next
next(({target, dispatch}) => { ... })
A convenient helper to pass a callback to process.nextTick. Can be used to manipulate the page in some way after a render. For example scrolling to a specific element
init
init(({target, dispatch}) => { ... })
Call init to mount your component. The callback is optional.
Application Code
store
store(seed)
It should return the agent.
agent
agent(commit, ...arguments)
Anything returned will be ignored
component
component({state, dispatch, next})
Should return the element to pass to diff
diff
diff(target, element)
- target: the target passed to framework
- element: the new element returned from the component
Related Projects