Created
June 23, 2017 07:30
-
-
Save kaheglar/a587286db24af724f4e2b31ee4e57eff to your computer and use it in GitHub Desktop.
Knockout server-side rendering - Making asynchronous components synchronous
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
const ko = require('knockout'); | |
ko.components.register('the-beatles', {require: 'the-beatles'}); |
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
const domino = require('domino'); | |
const html = ` | |
<!DOCTYPE html> | |
<html> | |
<body> | |
<the-beatles></the-beatles> | |
</body> | |
</html> | |
`; | |
const window = domino.createWindow(html); | |
const document = window.document; | |
global.document = document; | |
global.window = window; | |
const ko = require('knockout'); | |
// Load the application. | |
require('./app'); | |
// (Pre-)Load the components. | |
require('./the-beatles'); | |
const viewModel = {}; | |
const rootElement = document.documentElement; | |
ko.applyBindings(viewModel, rootElement); | |
console.log(rootElement.outerHTML); |
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
const ko = require('knockout'); | |
const theBeatles = { | |
template: ` | |
<ul data-bind="foreach: members"> | |
<li data-bind="text: $data"></> | |
</ul> | |
`, | |
viewModel: { | |
instance: { | |
members: [ | |
'John', | |
'Paul', | |
'George', | |
'Ringo' | |
] | |
} | |
}, | |
synchronous: true | |
}; | |
ko.components.unregister('the-beatles'); | |
ko.components.register('the-beatles', theBeatles); | |
module.exports = theBeatles; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To make this isomorphic you'll need a universal module format for the app and components, e.g. UMD.