1

I am building a settings module in a mean.js stack. And I want to re-use an existing function. But how? Here is some demo code:

controller-x.js

var mongoose = require( 'mongoose' ),
    errorHandler = require( './errors' ),
    time = require( 'time' ),
    _ = require( 'lodash' );


exports.create = function( req, res ) {
    // create something
};


exports.save = function( req, res ) {
    // save something
};

exports.update = function( req, res ) {
    // update something
};

How can i (re-)use the "save" function in the update or create, or some another function?

Scott Solmer
  • 3,871
  • 6
  • 44
  • 72
  • re-use how exactly? You could always create the function at the top, and just reference it `exports.save = fn;` and then call it other places `fn()`, but why ? – adeneo Nov 26 '14 at 17:52
  • Ahh man. He beat me to it :( – Pytth Nov 26 '14 at 17:56
  • @adeneo he wouldn't even have to create the function at the top. Anywhere in the file would work. – Ryan Nov 26 '14 at 17:57

2 Answers2

2

You could create the function elsewhere in the code, and simply reference it when the exports.save function is called, like this:

var someFunction = function(req, res) {
  ...logic for your save function...
};

exports.save = someFunction(req, res);

exports.update = function(req, res) {
  someFunction(req, res);
  ... And whatever other logic you want to use...
};
Pytth
  • 4,008
  • 24
  • 29
1

You could create a private method:

controller-x.js

var mongoose = require( 'mongoose' ),
    errorHandler = require( './errors' ),
    time = require( 'time' ),
    _ = require( 'lodash' );

var save = function( req, res ) {
    // save something
};   

exports.create = function( req, res ) {
    // create something
    save();
};


exports.save = save;

exports.update = function( req, res ) {
    // update something
};
Austin Pray
  • 4,926
  • 2
  • 22
  • 30