@${tweet.user.screen_name}
${tweet.text}
Functional approach to authoring performant HTML components using plugins
npm install fun-component<🙂/> 


Performant and functional HTML components with plugins. Syntactic suggar on top of nanocomponent.
- Usage
- API
- Lifecycle events
- Plugins
- Composition and forking
- Examples
- Why tho?
Pass in a function and get another one back that handles rerendering.
``javascript
// button.js
var html = require('nanohtml')
var component = require('fun-component')
var button = module.exports = component(function button (ctx, clicks, onclick) {
return html
})
// only bother updating if text changed
button.on('update', function (ctx, [clicks], [prev]) {
return clicks !== prev
})
`
`javascript
// app.js
var choo = require('choo')
var html = require('choo/html')
var button = require('./button')
var app = choo()
app.route('/', view)
app.mount('body')
function view (state, emit) {
return html
}app.use(function (state, emitter) {
state.clicks = 0
emitter.on('click', function () {
state.clicks += 1
emitter.emit('render')
})
})
`$3
Though fun-component was authored with choo in mind it works just as well standalone.
`javascript
var button = require('./button')var clicks = 0
function onclick () {
clicks += 1
button(clicks, onclick)
}
document.body.appendChild(button(clicks, onclick))
`API
$3
Create a new component context. Either takes a function as an only argument or a name and a function. Returns a function that renders the element. If no name is supplied the name is derrived from the functions
name property.Warning: implicit function names are most probably mangled during minification. If name consistency is important to your implementation, use the explicit name syntax.
`javascript
var button = component('button', (text) => html)
`####
button.on(name, fn)Add lifecycle event listener, see Lifecycle events.
####
button.off(name, fn)Remove lifecycle eventlistener, see Lifecycle events.
####
button.use(fn)Add plugin, see Plugins.
####
button.fork(name)Create a new component context inheriting listeners and plugins, see Composition and forking
$3
All the lifecycle hooks of nanocomponent are supported, i.e.
beforerender, load, unload, afterupdate, and afterreorder. Any number of listeners can be added for an event. The arguments are always prefixed with the component context and the element, followed by the render arguments.`javascript
var html = require('nanohtml')
var component = require('fun-component')var greeting = component(function greeting (ctx, name) {
return html
})greeting.on('load', function (ctx, el, name) {
console.log(
element ${name} is now in the DOM)
}greeting.on('afterupdate', function (ctx, el, name) {
console.log(
element ${name} was updated)
}document.body.appendChild(greeting('world'))
greeting('planet')
`#### Context
The component context (
ctx) is prefixed to the arguments of all lifecycle events and the render function itself. The context object can be used to access the underlying nanocomponent.`javascript
var html = require('nanohtml')
var component = require('fun-component')// exposing nanocomponent inner workings
module.exports = component(function time (ctx) {
return html
})
`#### Update
fun-component comes with a baked in default update function that performs a shallow diff of arguments to determine whether to update the component. By listening for the
update event you may override this default behavior.If you attach several
update listerners the component will update if any one of them return true.Note: Opposed to how nanocomponent calls the update function to determine whether to rerender the component, fun-component not only supplies the next arguments but also the previous arguments. These two can then be compared to determine whether to update.
Tip: Using ES2015 array deconstructuring makes this a breeze.
`javascript
var html = require('nanohtml')
var component = require('fun-component')var greeting = component(function greeting (ctx, name) {
return html
})// deconstruct arguments and compare
name
greeting.on('update', function (ctx, [name], [prev]) {
return name !== prev
})
`$3
Plugins are middleware functions that are called just before the component is rendered or updated. A plugin can inspect the arguments, modify the context object or even return another context object that is to be used for rendering the component.
`javascript
const html = require('nanohtml')
const component = require('fun-component')const greeter = component(function greeting (ctx, title) {
return html
})greeter.use(function log(ctx, title) {
console.log(
Rendering ${ctx._ncID} with ${title})
return ctx
})document.body.appendChild(greeter('world'))
`fun-component is bundled with with a handfull of plugins that cover the most common scenarios. Have you written a plugin you want featured in this list? Fork, add, and make a pull request.
- spawn – Spawn component contexts on demand and discard on unload.
- restate – Add state object and state management to the context object.
- logger – Add a logger (using nanologger) to the context object.
- cache – Cache element and reuse on consecutive mounts.
Examples
For example implementations, see /examples. Either spin them up locally or visit the link.
- Mapbox (using cache)
-
npm run example:mapbox
- https://fun-component-mapbox.now.sh
- List (using spawn)
- npm run example:list
- https://fun-component-list.now.sh
- Expandable (using spawn and restate)
- npm run example:expandable
- https://fun-component-expandable.now.sh$3
Using lifecycle event listeners and plugins makes it very easy to lazily compose functions by attaching and removing event listeners as needed. But you may sometimes wish to scope some listeners or plugins to a specific use case. To create a new component instance, inheriting all plugins and listeners, you may
fork a component.`javascript
// button.js
var html = require('nanohtml')
var component = require('fun-component')var button = module.exports = component(function button (ctx, text, onclick) {
return html
})// only bother with updating the text
button.on('update', function (ctx, [text], [prev]) {
return text !== prev
})
``javascript
// infinite-tweets.js
var html = require('nanohtml')
var component = require('fun-component')
var onIntersect = require('on-intersect')
var button = require('./button')module.exports = list
// fork button so that we can add custom behavior
var paginator = button.fork()
// automatically click button when in view
paginator.on('load', function (ctx, el, text, onclick) {
var disconnect = onIntersect(el, onclick)
paginator.on('unload', disconnect)
})
function list (tweets, paginate) {
return html
@${tweet.user.screen_name}
${tweet.text}
)}
}
`Why tho?
Authoring a component should be as easy as writing a function. Using arguments and scope to handle a components lifecycle is obvious and straight forward. Whereas having to worry about calling context and stashing things on
this` makes for cognitive overhead.Not for you? If you need more fine grained control or perfer a straight up object oriented programming approach, try using nanocomponent, it's what's powering fun-component behind the scenes.
- yoshuawuyts/microcomponent
- jongacnik/component-box
- choojs/nanocomponent
- choojs/nanohtml
- choojs/choo