Created
February 6, 2018 17:39
-
-
Save goto-bus-stop/199f66d289d71d87d8d3489caa6b1f7d to your computer and use it in GitHub Desktop.
choo mount idea
This file contains 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('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') | |
}) | |
} |
This file contains 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
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 | |
} | |
} |
This file contains 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>SSR example</title> | |
</head> | |
<body> | |
<!-- replaced by ssr.js --> | |
</body> | |
</html> |
This file contains 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 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