Last active
May 24, 2020 23:16
-
-
Save kristoferjoseph/77cf49b93adbaaf6b283a360ccebef04 to your computer and use it in GitHub Desktop.
Component prototype
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 html = require('bel') | |
var morph = require('nanomorph') | |
var inWindow = require('in-window') | |
var onload = require('on-load') | |
module.exports = function Component (options) { | |
options = options || {} | |
var template = options.template | |
var should = options.should || function () { return true } | |
var added = options.added | |
var removed = options.removed | |
return function instance () { | |
var element | |
var oldState | |
function init (state) { | |
element = onload(create(state), added, removed) | |
} | |
function create (state) { | |
var el = template(html, state) | |
oldState = state | |
return el | |
} | |
function update (state) { | |
if (should(oldState, state)) { | |
morph(element, create(state)) | |
} | |
} | |
function render (state) { | |
if (element) { | |
element.isSameNode = function () { | |
return should(oldState, state) | |
} | |
} | |
element && inWindow | |
? update(state) | |
: init(state) | |
return element | |
} | |
return render | |
}() | |
} |
var Component = require('☝️')
module.exports = Component({
template (html, state) {
var title = state && state.tile
return html`<h1>${title}</h1>`
},
should (oldState, newState) {
var ot = oldState && oldState.title
var nt = newState && newState.title
return ot === nt
},
added (el) {
console.info('ADDED TO DOM')
},
removed (el) {
console.info('REMOVED FROM DOM')
}
})
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: