Last active
March 9, 2017 19:55
-
-
Save jongacnik/6362eacb0c40c8fa1eb3af391949adbf to your computer and use it in GitHub Desktop.
Working cache-element implementation #js #nanocomponent #nanomorph @classnic
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
| var update = require('nanomorph/update') | |
| var widget = require('cache-element/widget') | |
| var h = require('bel') | |
| function superWidget (content) { | |
| return widget({ | |
| onload: function (el) { | |
| console.log('hello!') | |
| }, | |
| onunload: function (el) { | |
| console.log('bubye!') | |
| }, | |
| onupdate: function (el, state) { | |
| // this is where you can modify the | |
| // content *if* you so choose based | |
| // on the local state | |
| console.log('update', state) | |
| }, | |
| render: function (state) { | |
| console.log('render', state) | |
| return h`<button>${content}</button>` | |
| } | |
| }) | |
| } | |
| // this is important, we *must* store | |
| // a reference to our widgets in some | |
| // more *global* kind of place, obv a | |
| // good candidate is storing in state | |
| var wdgtInstances = [] | |
| function view () { | |
| if (!wdgtInstances.length) { | |
| console.log('create widgets, only do this once!') | |
| wdgtInstances = [ | |
| superWidget('Neat!'), | |
| superWidget('Cute!') | |
| ] | |
| } | |
| // date passed in to force a contrived | |
| // update for this example | |
| return h` | |
| <div>${wdgtInstances.map(w => w(Date.now()))}</div> | |
| ` | |
| } | |
| var tree = view() | |
| var morph = update(tree) | |
| document.body.appendChild(tree) | |
| // morph w/o re-render! | |
| morph(view(), tree) | |
| morph(view(), tree) | |
| morph(view(), tree) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment