Table of Contents
Event listening
on
prependListener
once
Event triggering
this points to
Asynchronous call
Event unloading
off/removeListener
removeAllListeners
Home Web Front-end JS Tutorial Detailed explanation of events in Node.js

Detailed explanation of events in Node.js

Dec 01, 2020 pm 05:34 PM
node.js event

Detailed explanation of events in Node.js

Related recommendations: "nodejs Tutorial"

The front-end is certainly no stranger to events, binding the scroll event for the window

window.addEventListener('scroll', ev => {
	console.log(ev);
});
Copy after login

Node.js Most asynchronous operations are event-driven. All objects that can trigger events inherit the EventEmitter class

Event listening

on

Node.js event listening is very similar to jQuery APIemitter.on(eventName, listener)

const ee = new EventEmitter();
ee.on('foo', () => console.log('a'));
Copy after login
  1. EventEmitter instance will maintain a listener array, and each listener defaults Will be added to the end of the array
  2. Every time a listener is added, it will not be checked whether it has been added. Calling on multiple times and passing in the same eventName and listener will cause the listener to be added multiple times

prependListener

emitter.prependListener(eventName, listener)
You can add the listener to the head of the listener array through prependListener

const ee = new EventEmitter();
ee.prependListener('foo', () => console.log('a'));
Copy after login

once

If you want the listener to be triggered once and then no longer trigger, you can use once to bind the event

const ee = new EventEmitter();
ee.once('foo', () => console.log('a'));
Copy after login

Event triggering

emitter.emit(eventName[, ... args])
Most of the developer's event-related work in the browser environment is to subscribe to events, that is, to bind the event processing function listener. In Node.js event programming, it is often necessary to create event objects. The actual trigger event. Use the emit method to synchronously call each listener registered to the event named eventName in the order of listener registration, and pass in the provided parameters

const EventEmitter = require('events');
const myEmitter = new EventEmitter();

// 第一个监听器。
myEmitter.on('event', function firstListener() {
  console.log('第一个监听器');
});
// 第二个监听器。
myEmitter.on('event', function secondListener(arg1, arg2) {
  console.log(`第二个监听器中的事件有参数 ${arg1}、${arg2}`);
});
// 第三个监听器
myEmitter.on('event', function thirdListener(...args) {
  const parameters = args.join(', ');
  console.log(`第三个监听器中的事件有参数 ${parameters}`);
});

console.log(myEmitter.listeners('event'));

myEmitter.emit('event', 1, 2, 3, 4, 5);

// Prints:
// [
//   [Function: firstListener],
//   [Function: secondListener],
//   [Function: thirdListener]
// ]
// 第一个监听器
// 第二个监听器中的事件有参数 1、2
// 第三个监听器中的事件有参数 1, 2, 3, 4, 5
Copy after login

this points to

eventEmitter.emit() The method can pass any number of parameters to the listener. this The keyword will be pointed to the EventEmitter instance bound to the listener

const myEmitter = new MyEmitter();
myEmitter.on('event', function(a, b) {
  console.log(a, b, this, this === myEmitter);
  // 打印:
  //   a b MyEmitter {
  //     domain: null,
  //     _events: { event: [Function] },
  //     _eventsCount: 1,
  //     _maxListeners: undefined } true
});
myEmitter.emit('event', 'a', 'b');
Copy after login

You can also use ES6 arrow functions as listeners. But this keyword will not point to the EventEmitter instance:

const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
  console.log(a, b, this);
  // 打印: a b {}
});
myEmitter.emit('event', 'a', 'b');
Copy after login

Asynchronous call

EventEmitter Call all listeners synchronously in the order of registration, so that To ensure the correct ordering of events, the listener can use the setImmediate() and process.nextTick() methods to switch to asynchronous operation mode

const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
  setImmediate(() => {
    console.log('异步地发生');
  });
});
myEmitter.emit('event', 'a', 'b');
Copy after login

Event unloading

Node.js provides several methods for uninstalling event bindings

off/removeListener

The off method is an alias of the removeListener method and is used to clean up event bindings emitter.removeListener(eventName, listener)

const callback = (stream) => {
  console.log('已连接');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
Copy after login

removeListener() will only remove at most one listener from the listener array. If a listener is added multiple times to the listener array for a specified eventName, removeListener() must be called multiple times to remove all instances

removeAllListeners

emitter. removeAllListeners([eventName])
Remove the listener of the specified eventName event. If eventName is not specified, remove all listeners of the event object. You can get the eventName array on the event object through emitter.eventNames()

const EventEmitter = require('events');
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});

myEE.eventNames().forEach(eventName => myEE.removeAllListeners);
Copy after login

For more programming-related knowledge, please visit: Programming Video! !

The above is the detailed content of Detailed explanation of events in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Event ID 4660: Object deleted [Fix] Event ID 4660: Object deleted [Fix] Jul 03, 2023 am 08:13 AM

Some of our readers encountered event ID4660. They're often not sure what to do, so we explain it in this guide. Event ID 4660 is usually logged when an object is deleted, so we will also explore some practical ways to fix it on your computer. What is event ID4660? Event ID 4660 is related to objects in Active Directory and will be triggered by any of the following factors: Object Deletion – A security event with Event ID 4660 is logged whenever an object is deleted from Active Directory. Manual changes – Event ID 4660 may be generated when a user or administrator manually changes the permissions of an object. This can happen when changing permission settings, modifying access levels, or adding or removing people or groups

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

Get upcoming calendar events on your iPhone lock screen Get upcoming calendar events on your iPhone lock screen Dec 01, 2023 pm 02:21 PM

On iPhones running iOS 16 or later, you can display upcoming calendar events directly on the lock screen. Read on to find out how it's done. Thanks to watch face complications, many Apple Watch users are used to being able to glance at their wrist to see the next upcoming calendar event. With the advent of iOS16 and lock screen widgets, you can view the same calendar event information directly on your iPhone without even unlocking the device. The Calendar Lock Screen widget comes in two flavors, allowing you to track the time of the next upcoming event, or use a larger widget that displays event names and their times. To start adding widgets, unlock your iPhone using Face ID or Touch ID, press and hold

Let's talk about the event loop in Node Let's talk about the event loop in Node Apr 11, 2023 pm 07:08 PM

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

Learn more about Buffers in Node Learn more about Buffers in Node Apr 25, 2023 pm 07:49 PM

At the beginning, JS only ran on the browser side. It was easy to process Unicode-encoded strings, but it was difficult to process binary and non-Unicode-encoded strings. And binary is the lowest level data format of the computer, video/audio/program/network package

An article to talk about how to efficiently develop presentation layer Node.js applications An article to talk about how to efficiently develop presentation layer Node.js applications Apr 17, 2023 pm 07:02 PM

How to use Node.js for front-end application development? The following article will introduce you to the method of developing front-end applications in Node, which involves the development of presentation layer applications. The solution I shared today is for simple scenarios, aiming to allow front-end developers to complete some simple server-side development tasks without having to master too much background knowledge and professional knowledge about Node.js, even if they have no coding experience.

See all articles