Skip to content

Instantly share code, notes, and snippets.

@goto-bus-stop
Created February 6, 2018 17:39
Show Gist options
  • Save goto-bus-stop/199f66d289d71d87d8d3489caa6b1f7d to your computer and use it in GitHub Desktop.
Save goto-bus-stop/199f66d289d71d87d8d3489caa6b1f7d to your computer and use it in GitHub Desktop.
choo mount idea
var html = require('choo/html')
var choo = require('choo')
var app = choo()
app.use(countStore)
app.route('/', mainView)
module.exports = app.mount('body') // Mount & expose.
function mainView (state, emit) {
return html`
<body>
<h1>count is ${state.count}</h1>
<button onclick=${onclick}>Increment</button>
</body>
`
function onclick () {
emit('increment', 1)
}
}
function countStore (state, emitter) {
state.count = 0
emitter.on('increment', function (count) {
state.count += count
emitter.emit('render')
})
}
Choo.prototype.mount = function (target) {
if (typeof target === 'string') this._selector = target
else this._selector = target.nodeName // or something
if (typeof window !== 'undefined') {
// normal browser mount() code
} else {
// on the server
return this
}
}
<!DOCTYPE html>
<html>
<head>
<title>SSR example</title>
</head>
<body>
<!-- replaced by ssr.js -->
</body>
</html>
var app = require('./app')
var hstream = require('hstream')
var body = app.toString('/')
var selector = app._selector
var transform = hstream({
// Replace element matched by $selector w/ the server rendered body.
// Taking the selector from the app instance so we can support things
// like app.mount('#app') being rendered into a <div id="app"></div>
[selector]: { _replaceHtml: body }
})
fs.createReadStream('index.html')
.pipe(transform)
.pipe(process.stdout)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment