nodejs的事件实现类似:
app.use(function (req, res, next) {
cosole.log(res)
next()
})
app.post(...)
类似上面,需要实现类似的事件效果:
event.watch('all', cb)
event.watch('[event type]', cb)
就是监控所有事件并作出反馈但不会影响事件的单独执行。这里使用once和emit创建触发事件
PHP中文网2017-04-17 14:52:20
The following content is mainly divided into two parts:
Express middleware is roughly implemented.
The subject’s last question.
First, let’s briefly talk about how the routing middleware in express is implemented. (In order to reduce complexity, we will not talk about the implementation of route splitting here)
express
internally maintains a data called stack
. When the user calls a route registration method like app.post(path, fn)
, a route instance will be added to stack
. Abstractly, this routing instance is considered here as {path: path, handler: fn}
, where path
is the path corresponding to the route, and handler
is the corresponding middleware.
is more special than app.all(path, fn)
. In fact, the internal implementation is not complicated. It can be roughly thought of as traversing all htp methods supported by node, and then calling the route registration method, such as app.get(path, fn)
, app.post(path, fn)
...(The internal implementation is more clever than this, not so crude)
When a network request comes in, express
will internally detect the http method and path of the request, and then traverse the stack
array. If method相同 且 路由命中
is satisfied at the same time, then the corresponding middleware will be called.
method相同 且 路由命中
, so how do you implement the sequential invocation of multiple middlewares? That’s it next
. (Implementation omitted)
Back to the "event effect" in the question. Refer to the above steps and you will basically know how to implement it.