有人知道将上下文传递给 sails Controller 操作的正确方法吗? 这是我的案例,为什么我想这样做:
--- AbstractPageController.js ---
module.exports = {
_getPageData: function(req, res) {
return {
data: {
title: this._getTitle(req, res), // if do nothing "this" is global object
menu: this._getMenu(req, res)
}
};
},
_getTitle: function(req, res) { return 'Cool Page'; },
_getMenu: function(req, res) { return [{ href: '/logout' }]; }
};
--- ConcretePageController.js ---
var _ = require('lodash');
_super = require('./AbstractPageController.js');
module.exports = _.merge({}, _super, {
'main': function(req, res) {
res.view('pageTemplate', this._getPageData(req, res));
},
_getTitle: function(req, res) {
return 'Absolutely - ' + _super._getTitle(req, res);
},
_getMenu: function(req, res) {
return [{ href: '/main/'}].concat(_super._getMenu(req, res));
}
});
这就是为什么我需要上下文。
对于这个特殊情况,我找到了这个解决方案:
---routes.js ---
var concreteController = require('../api/controllers/ConcretePageController.js');
module.exports.routes = {
'/concrete_page': function(req, res) { concreteController.main(req, res); }
}
但这看起来有点丑陋,并且 sails 钩(例如策略)停止工作。
我正在考虑另一种方式。其要点是将所有逻辑移至服务并使用简单的继承。但这对我来说也很奇怪
有什么更好的方法来处理我写的案例吗?
附注我上面编写的所有代码只是一个示例。
最佳答案
我想您想要预先设置一些数据以发送到 View 模板,对吗?
是的,你可以使用一个Before hook(如中间件)或sails Police
我使用 sails hook 来预加载 we-plugin 中 npm 模块的 sails 功能 https://github.com/wejs/we-plugin
检查此 Hook 以了解如何在 Controller 之后的所有请求中加载用户区域设置: 链接:https://github.com/wejs/we-example/blob/master/api/hooks/we-locale/index.js#L15
关于javascript - SailsJs Controller 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26398638/