简体   繁体   English

this.on事件处理程序从哪里来? 是图书馆吗?

[英]Where is the this.on event handler coming from? Is it a library?

I'm casually reading application.js from the express source code. 我从随便的源代码中读取application.js。

Where is this event .on coming from? 这个事件从哪里来? Is this plain old javascript or is there some library that provides this event pattern? 这是普通的旧JavaScript还是有提供此事件模式的库?

 this.on('mount', function onmount(parent) {
    // inherit trust proxy
    if (this.settings[trustProxyDefaultSymbol] === true
      && typeof parent.settings['trust proxy fn'] === 'function') {
      delete this.settings['trust proxy'];
      delete this.settings['trust proxy fn'];
    }

https://github.com/expressjs/express/blob/master/lib/application.js#L89 https://github.com/expressjs/express/blob/master/lib/application.js#L89

app , the application prototype (which is defined in /lib/application.js and used in /lib/express.js ) is given the methods of an EventEmitter , which is a Node built-in type. app ,该应用程序的原型(在定义/lib/application.js和中使用/lib/express.js )被给予的方法EventEmitter ,这是节点内置类型。

In the current version of the code, this is done in /lib/express.js with the line 在当前版本的代码中,这是在/lib/express.js使用以下行完成的:

mixin(app, EventEmitter.prototype, false);

where mixin is from the merge-descriptors package. 其中mixin来自merge-descriptors包。

From Node JS documentation : Node JS文档中

All objects that emit events are instances of the EventEmitter class. 所有发出事件的对象都是EventEmitter类的实例。 These objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object. 这些对象公开了eventEmitter.on()函数,该函数允许将一个或多个函数附加到该对象发出的命名事件。

The this on that line is an instance of the express app, which, seen here inherits all the methods from EventEmitter (including on() ). 该行上的this是express应用程序的实例,在这里可以看到 ,它继承了EventEmitter的所有方法(包括on() )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM