Skip to content

Instantly share code, notes, and snippets.

@kaheglar
Created June 23, 2017 07:30
Show Gist options
  • Save kaheglar/a587286db24af724f4e2b31ee4e57eff to your computer and use it in GitHub Desktop.
Save kaheglar/a587286db24af724f4e2b31ee4e57eff to your computer and use it in GitHub Desktop.
Knockout server-side rendering - Making asynchronous components synchronous
const ko = require('knockout');
ko.components.register('the-beatles', {require: 'the-beatles'});
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);
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;
@kaheglar
Copy link
Author

kaheglar commented Jun 23, 2017

To make this isomorphic you'll need a universal module format for the app and components, e.g. UMD.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment