template rendering with node.js and backbone.js

后端 未结 9 1331
孤城傲影
孤城傲影 2021-02-01 08:20

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

9条回答
  •  灰色年华
    2021-02-01 08:59

    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.

提交回复
热议问题