1

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?

JQuery Mobile
  • 5,661
  • 21
  • 68
  • 126

1 Answers1

0

As far as node is concerned, you can use the same name viewModel in more than one file. But for your own sanity and clarity of thought I'd recommend using different names, as you suggested. When you asked the question, "how do I populate the view model?", I had to go back and read through the code for a couple of seconds to see which view model you meant. When you program grows from 40 lines to 4000 lines it will become a lot hard to keep the models straight if they all have the same name.

As for the POST data, you can access the POST data using the req.body property. This questions is already answered here: How do you extract POST data in Node.js?

Community
  • 1
  • 1
Lee Jenkins
  • 1,804
  • 2
  • 16
  • 34