Has anyone found a good solution for developing templates for backbone.js that can be used on the server and the client?
This is really desirable with the backbone.js hi
You could use JSDOM to render your page with node.js as follows
// specify a catch all route
app.get('/namespace/*', function (req, res, next) {
// load the dom
jsdom.env({
html: html,
src: src,
features: {
FetchExternalResources: false,
ProcessExternalResources: false
},
done: function (err, window) {
// overwrite Backbone's sync method with a server-side one
window.Backbone.sync = sync
window.$(function () {
window.Backbone.history.start({ silent: true })
// load requested url
var matched = window.Backbone.history.loadUrl(req.originalUrl.substr(1))
if (matched) // if matched: return resulting html
res.end(window.document.innerHTML)
else
next()
})
}
})
})
Therefor you also have to specify the following variables
var sync = function(method, model, options, error) {
// your server side sync method
}
var html = fs.readFileSync(path.join(__dirname, 'views/index.htm'), 'utf-8')
var src = [
fs.readFileSync(path.join(__dirname, 'public/javascripts/jquery.js'), 'utf-8'),
fs.readFileSync(path.join(__dirname, 'public/javascripts/underscore.js'), 'utf-8'),
fs.readFileSync(path.join(__dirname, 'public/javascripts/backbone.js'), 'utf-8'),
fs.readFileSync(path.join(__dirname, 'public/javascripts/your-backbone-stuff.js'), 'utf-8')
]
Unfortunately I didn't found a solution to duplicate the created window/document object for reuse.
Also this solutions is only suitable for e.g. search engines because it lacks the client-side mapping from Backbone Views to there corresponding DOM nodes.