From a23dc51397897fc03f958b4a208654b7c4b33886 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9e=20Kooi?= Date: Tue, 13 Feb 2018 22:09:08 +0100 Subject: [PATCH] server: Store mount selector and return `this` (#625) * Store mount selector and return `this` This allows `.mount('body')` to be used on the server like so: ```js module.exports = app.mount('body') ``` Then, when server rendering you can do: ```js var app = require('./app') fillServerTemplate(html, app.selector, app.toString('/')) ``` Where `fillServerTemplate` is a function that replaces the HTML at a CSS selector with some string. This way you do not need to check for `typeof window` in your application entry point to do server rendering, and it allows tools like bankai to automatically inline server rendered html in the correct place. * docs * better words --- README.md | 11 ++++++++++- index.js | 7 ++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3c0e27c..db256d8 100644 --- a/README.md +++ b/README.md @@ -459,9 +459,18 @@ See [#routing](#routing) for an overview of how to use routing efficiently. Start the application and mount it on the given `querySelector`, the given selector can be a String or a DOM element. -This will _replace_ the selector provided with the tree returned from `app.start()`. +In the browser, this will _replace_ the selector provided with the tree returned from `app.start()`. If you want to add the app as a child to an element, use `app.start()` to obtain the tree and manually append it. +On the server, this will save the `selector` on the app instance. +When doing server side rendering, you can then check the `app.selector` property to see where the render result should be inserted. + +Returns `this`, so you can easily export the application for server side rendering: + +```js +module.exports = app.mount('body') +``` + ### `tree = app.start()` Start the application. Returns a tree of DOM nodes that can be mounted using `document.body.appendChild()`. diff --git a/index.js b/index.js index 96001aa..03eb04b 100644 --- a/index.js +++ b/index.js @@ -153,7 +153,12 @@ Choo.prototype.start = function () { } Choo.prototype.mount = function mount (selector) { - assert.equal(typeof window, 'object', 'choo.mount: window was not found. .mount() must be called in a browser, use .toString() if running in Node') + if (typeof window !== 'object') { + assert.ok(typeof selector === 'string', 'choo.mount: selector should be type String') + this.selector = selector + return this + } + assert.ok(typeof selector === 'string' || typeof selector === 'object', 'choo.mount: selector should be type String or HTMLElement') var self = this