我正在构建一个mean.js堆栈中的设置模块。我想重新使用现有的功能。但是怎么样?这是一些演示代码:
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
};
我如何(重新)在更新或创建或其他功能中使用“保存”功能?
答案 0 :(得分:2)
您可以在代码中的其他位置创建函数,并在调用exports.save
函数时简单地引用它,如下所示:
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...
};
答案 1 :(得分:1)
您可以创建一个私有方法:
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
};