Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Last active March 21, 2018 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barneycarroll/94d54e7310408803e085122b5894a451 to your computer and use it in GitHub Desktop.
Save barneycarroll/94d54e7310408803e085122b5894a451 to your computer and use it in GitHub Desktop.
const Historian = Object.assign(
Component => {
const histories = new WeakMap
return {
onbeforeupdate({}, old){
if(Component.onbeforeupdate && Component.onbeforeupdate.apply(this, arguments) === false)
return false
histories.set(old.state, old)
},
...['view', 'oninit', 'oncreate', 'onupdate', 'onbeforeremove', 'onbeforeremove']
.map(key => Component[key] && ({
[key] : v => Component[key](v.state, v, histories.get(v.state))
}))
.reduce((a,b) => Object.assign(a,b), {}),
}
},
onbeforeupdate : ({}, old) =>
old.state.old = old,
view: v =>
v.children[0].children(v.state.old.instance)
)

Use as a decorator:

const Component = Historian({
  view: (vnode, oldVnode) => ''
})

...or as a functor component:

m(Historian, oldVnode => '')

The decorator enables you to write single-depth, easily invoked reusable components with baked-in behaviour; meanwhile the functor component enables you to reference previous nodes of a different type in place (useful for transitions!).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment