Skip to content

Commit a23dc51

Browse files
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
1 parent 658a399 commit a23dc51

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

README.md

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -459,9 +459,18 @@ See [#routing](#routing) for an overview of how to use routing efficiently.
459459
Start the application and mount it on the given `querySelector`,
460460
the given selector can be a String or a DOM element.
461461

462-
This will _replace_ the selector provided with the tree returned from `app.start()`.
462+
In the browser, this will _replace_ the selector provided with the tree returned from `app.start()`.
463463
If you want to add the app as a child to an element, use `app.start()` to obtain the tree and manually append it.
464464

465+
On the server, this will save the `selector` on the app instance.
466+
When doing server side rendering, you can then check the `app.selector` property to see where the render result should be inserted.
467+
468+
Returns `this`, so you can easily export the application for server side rendering:
469+
470+
```js
471+
module.exports = app.mount('body')
472+
```
473+
465474
### `tree = app.start()`
466475
Start the application. Returns a tree of DOM nodes that can be mounted using
467476
`document.body.appendChild()`.

index.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,12 @@ Choo.prototype.start = function () {
153153
}
154154

155155
Choo.prototype.mount = function mount (selector) {
156-
assert.equal(typeof window, 'object', 'choo.mount: window was not found. .mount() must be called in a browser, use .toString() if running in Node')
156+
if (typeof window !== 'object') {
157+
assert.ok(typeof selector === 'string', 'choo.mount: selector should be type String')
158+
this.selector = selector
159+
return this
160+
}
161+
157162
assert.ok(typeof selector === 'string' || typeof selector === 'object', 'choo.mount: selector should be type String or HTMLElement')
158163

159164
var self = this

0 commit comments

Comments
 (0)