Created
January 4, 2019 12:17
-
-
Save tornqvist/850a0b6f0844d8a9f9b48ff6d4cf4192 to your computer and use it in GitHub Desktop.
Lazy Choo component using split-require
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 Choo = require('choo') | |
var html = require('choo/html') | |
var LazyColor = require('./lazy-color') | |
var app = new Choo() | |
app.use(store) | |
app.route('/', view) | |
app.mount('body') | |
function view (state, emit) { | |
return html` | |
<body> | |
<select onselect=${onselect}> | |
<option disabled>Pick a color</option> | |
<option selected=${state.color === 'blue'}>blue</option> | |
<option selected=${state.color === 'pink'}>pink</option> | |
<option selected=${state.color === 'red'}>red</option> | |
</select> | |
${state.color ? state.cache(LazyColor, state.color) : null} | |
</body> | |
` | |
function onselect (event) { | |
emit('color', event.target.value) | |
} | |
} | |
function store (state, emitter) { | |
state.color = null | |
emitter.on('color', function (color) { | |
state.color = color | |
emitter.emit('render') | |
}) | |
} |
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 Component = require('choo/component') | |
var splitRequire = require('split-require') | |
var colors = { | |
'blue': () => splitRequire('./blue'), | |
'pink': () => splitRequire('./pink'), | |
'red': () => splitRequire('./red') | |
} | |
module.exports = class LazyColor extends Component { | |
constructor (id, state, emit, color) { | |
super(id) | |
this.emit = emit | |
this.component = null | |
this.local = state.components[id] = { | |
color: color, | |
id: id | |
} | |
} | |
update () { | |
reutrn true | |
} | |
load () { | |
this.emit('loading', this.local.color) | |
var load = colors[this.local.color] | |
load().then((Color) => { | |
this.component = new Color() | |
this.emit('loaded', this.local.color) | |
this.rerender() | |
}) | |
} | |
createElement (...args) { | |
if (!this.component) return html`<span>Loading…</span>` | |
return this.component.render(...args) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment