Rya*_*ott 13 model-view-controller node.js express
在快速路线上,传统控制器有什么不同或更强大的功能吗?
如果您有快速应用程序并定义模型,它是否成为MVC应用程序,还是更有必要?
我只是想知道我是否错过了我的节点快递应用程序中的额外/更简单的功能,而不是升级到更合法的"控制器".如果有这样的事情.
谢谢!
编辑:澄清一下,如果你使用这样的路线:
// routes/index.js
exports.module = function(req, res) {
// Get info from models here,
res.render('view', info: models);
}
Run Code Online (Sandbox Code Playgroud)
是什么让它与控制器有什么不同?控制器能够做得更多吗?
Pic*_*els 14
首先,express中的路由是connect中定义的中间件.express和其他框架之间的区别在于中间件大多位于控制器前面,控制器结束响应.express使用中间件的另一个原因是Node.js的性质是异步的.
让我们看看Javascript中控制器的外观.
var Controller = function () { };
Controller.prototype.get = function (req, res) {
find(req.param.id, function (product) {
res.locals.product = product;
find(res.session.user, function (user) {
res.locals.user = user;
res.render('product');
});
});
};
Run Code Online (Sandbox Code Playgroud)
你可能会注意到这个get动作的第一件事是嵌套回调.这很难测试,难以阅读,如果你需要编辑东西,你需要摆弄你的缩进.因此,我们通过使用流量控制并使其平坦来解决这个问题.
var Controller = function () { };
Controller.prototype.update = function (req, res) {
var stack = [
function (callback) {
find(req.param.id, function (product) {
res.locals.product = product;
callback();
});
},
function (callback) {
find(res.session.user, function (user) {
res.locals.user = user;
callback();
});
}
];
control_flow(stack, function (err, result) {
res.render('product');
});
}
Run Code Online (Sandbox Code Playgroud)
在此示例中,您可以提取堆栈的所有不同功能并对其进行测试,甚至可以将它们重新用于不同的路由.您可能已经注意到控制流结构看起来很像中间件.因此,让我们在路由中用中间件替换堆栈.
app.get('/',
function (req, res, next) {
find(req.param.id, function (product) {
res.locals.product = product;
next();
});
},
function (req, res, next) {
find(res.session.user, function (user) {
res.locals.user = user;
next();
});
},
function (req, res, next) {
res.render('product');
}
);
Run Code Online (Sandbox Code Playgroud)
因此,虽然技术上可能在express.js中有控制器,但您可能会被迫使用流控制结构,这最终与中间件相同.
| 归档时间: |
|
| 查看次数: |
6963 次 |
| 最近记录: |