Created
June 29, 2019 12:12
-
-
Save sergey-shpak/c1e0db3d52019eecb0b5717e8cbf00ad to your computer and use it in GitHub Desktop.
Hyperapp#2 lifecycle events helper
This file contains 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 { h } from 'hyperapp' | |
import Lifecycle, { withChildLifeCycle } from 'lifecycle' | |
// 'customEvent.detail' contains element triggered lifecycle event | |
// please use effects to properly manipulate dom element | |
const action = (state, customEvent) => state | |
// and somewhere | |
<Lifecycle> | |
<div oncreated={ action }>created</div> | |
</Lifecycle> | |
// or | |
{ withChildLifeCycle(<form> | |
<input type="text" oncreated={ action } /> | |
</form>) } |
This file contains 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 { h } from 'hyperapp' | |
const wrap = (method, eventName) => function (el){ | |
const event = new CustomEvent(eventName, { detail: el }) | |
setTimeout(() => el.dispatchEvent(event)) | |
return Object.getPrototypeOf(this)[method].call(this, el) | |
} | |
export const withChildLifeCycle = node => { | |
return { ...node, props: { | |
appendChild: wrap('appendChild', 'create'), | |
removeChild: wrap('removeChild', 'remove'), | |
...node.props | |
}} | |
} | |
export default (props, child) => | |
withChildLifeCycle(<div {...props} >{ child }</div>) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for providing this answer. It took me the morning to arrive here :)
I'm including a working example for those new to hyperapp like myself,
index.html
, I'm using [email protected] so I had to change event name to camel case,onCreate
lifecycle.js
to avoid jsx build step (last export)