简体   繁体   中英

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

I'm casually reading application.js from the express source code.

Where is this event .on coming from? Is this plain old javascript or is there some library that provides this event pattern?

 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

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.

In the current version of the code, this is done in /lib/express.js with the line

mixin(app, EventEmitter.prototype, false);

where mixin is from the merge-descriptors package.

From Node JS documentation :

All objects that emit events are instances of the EventEmitter class. These objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object.

The this on that line is an instance of the express app, which, seen here inherits all the methods from EventEmitter (including on() ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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