你可以有一个控制器类,它的构造函数接受一个 express 对象,为你设置路由。所以这是一个示例基Controller
类:
/**
* @param connect can either be Sencha Labs' `connect` module, or
*/
function Controller(express) {
var self = this;
var name = '/' + this._name;
express.post(name, function (req, res, next) {
self._create(req, res, next);
});
express.get(name, function (req, res, next) {
self._read(req, res, next);
});
express.put(name + '/:id', function (req, res, next) {
self._update(req, res, next);
});
express.delete(name + '/:id', function (req, res, next) {
self._delete(req, res, next);
});
}
// Since there aren't any protected variables in JavaScript, use
// underscores to tell other programmers that `name` is protected. `name`
// (or, more technically, `_name`) is still accessible, but at least, if a
// team is disciplined enough, they'd know better than to access variables
// with underscores in them.
Controller.prototype._name = '';
Controller.prototype._create = function (req, res, next) {
};
Controller.prototype._read = function (req, res, next) {
};
Controller.protoype._update = function (req, res, next) {
};
Controller.prototype._delete = function (req, res, next) {
};
Users
然后,您可以通过从Controller
“类”扩展来创建控制器:
function UsersController(express) {
Controller.call(this, express);
}
// This is not the most perfect way to implement inheritance in JavaScript,
// this is one of the many ways.
UsersController.prototype = Controller.prototype;
UsersController.prototype._name = 'users'
// An example override of the base `Controller#create` method.
UsersController.prototype._create = function (req, res, next) {
db.save(req.body, function (err) {
if (err) res.send(500, err.message);
res.redirect('/');
});
};
UsersController.prototype._read = function (req, res, next) {
db.read(function (err, users) {
if (err) res.send(500, err.message);
res.send(users);
});
};
一旦你声明和定义了所有适当的控制器,你就可以开始在你的 express 应用程序中实现它们。
// Initialize a new instance of your controller.
var usersController = new UsersController(app);
PS:对于构造函数中的快速调用,还有另一种方法可以添加您的create
, read
, update
,delete
路由(以及任何其他路由)。一开始我只是不想让你感到困惑。
function Controller(express) {
var name = '/' + this._name;
express.post(name, this._create.bind(this));
express.get(name, this._read.bind(this));
express.put([name , ':id'].join('/'), this._update.bind(this));
express.delete([name, ':id'].join('/'), this._delete.bind(this));
};