I'm learning Node.js. At this time, I am using ES6, Node, and Express. I am concerned about the scope of my view model. At this time, I have the following:
server.js
// setup the routing
var routes = require('./routes');
app.use('/', routes.home);
The routes are properly registering. I have my routes defined in $projectDir/routes/home.js. That file looks like this:
home.js
var router = require('express').Router();
/* GET the main page. */
router.get('/', function(req, res) {
var viewModel = require('../viewModels/home/index');
res.render('home/index', viewModel);
});
/* GET the contact page. */
router.get('/contact', function(req, res) {
var viewModel = require('../viewModels/home/contact');
res.render('home/contact', viewModel);
});
/* POST contact information */
router.post('/contact', function(req, res) {
// ?
});
That approach works just fine. I've defined my view models at $projectDir/viewModels/home/index.js and $projectDir/viewModels/home/contact.js.
index.js
var viewModel = {
title: '',
constructor() {
this.title = 'Welcome';
}
};
module.exports = viewModel;
contact.js
var viewModel = {
title: '',
emailAddress: '',
constructor() {
this.title = 'Contact Us';
}
};
module.exports = viewModel;
I have concerns around the scope of view model. First, I'm using module.exports = viewModel;
in two separate files. Is this ok? Or should I name the variables something like indexViewModel
and contactViewModel
? Also, when a POST happens, how do I populate use the view model with the values that the user entered into a form? For example their email address?