Node. js Event

Source: Internet
Author: User
Tags emit

Node. js Event

All asynchronous I/O operations of node. JS send an event to the event queue when it is finished.

Many objects in node. JS Distribute Events: A Net.server object distributes an event every time a new connection is made, and an Fs.readstream object emits an event when the file is opened. All the objects that generated the event are events. An instance of Eventemitter. You can access the module by require ("events").

Let's use a simple example to illustrate the use of Eventemitter:

var eventemitter = require (  ' events 'varnew eventemitter ();   Event.on (function() {     console.log (' some_event occured. ') ); }); SetTimeout (function() {     event.emit (' some_event ')

Run this code, 1 seconds after the console output ' some_event occured '. The principle is that the event object registers a listener for events some_event, and then we send an event some_event to the event object by SetTimeout after 1000 milliseconds, and Some_event listener is called.

Eventemitter Introduction

The events module provides only one object: events. Eventemitter. The core of Eventemitter is the encapsulation of event launch and event listener functionality.

Each event of the Eventemitter consists of an event name and several parameters, which is a string that usually expresses a certain semantics. For each event, Eventemitter supports a number of event listeners.

When an event is emitted, the event listener registered to the event is called sequentially, and the event arguments are passed as a callback function parameter.

Let's explain the process in the following example:

var events = require (' Events 'varnew  events. Eventemitter (); Emitter.on (function(arg1, arg2) {     console.log (' listener1 ', arg1, arg2);}); Emitter.on (function(arg1, arg2) {     console.log (' Listener2 ', arg1, arg2);}); Emitter.emit (

The result of the operation is:

Listener1 Byvoid 1991

In the example above, emitter registered two event listeners for event Someevent and then fired the Someevent event. You can see that two event listener callback functions were called in the running results. This is the simplest use of eventemitter.

Eventemitter Common APIs

Eventemitter.on (event, listener), Emitter.addlistener (event, listener) registers a listener for the specified event, accepting a string event and a callback function listener.

function (stream) {  console.log (' Someone connected! ') );});
Eventemitter.emit (event, [Arg1], [arg2], [...]) launches event, passing several optional parameters to the event listener's parameter table.

Eventemitter.once (event, listener) registers a single listener for the specified event, that is, the listener is fired at most once, and the listener is released immediately after the trigger.

function (stream) {  console.log (' Ah, we have our first user! ' );});

Eventemitter.removelistener (event, listener) removes a listener for the specified event, listener must be a listener that the event has already registered.

var function (stream) {  console.log (' Someone connected! ') );}; Server.on (' connection ', callback); //  ... Server.removelistener (' Connection ', callback);

Eventemitter.removealllisteners ([Event]) removes all listeners for all events and, if specified, removes all listeners for the specified event.

Error Event

Eventemitter defines a special event error, which contains the semantics of "error", and we usually emit an error event when we encounter an exception.

When error is fired, eventemitter specifies that if there is no response listener, node. JS will treat it as an exception, exit the program and print the call stack.

We typically set up listeners for the object that will emit the error event, to avoid the entire program crashing after encountering errors. For example:

var events = require (' Events 'var emitter = newevents. Eventemitter (); Emitter.emit (

The following error is displayed at run time:

Throw //  ^' Error ' event. At Eventemitter.emit (events.js:50:15) at Object. <anonymous> (/home/byvoid/error.js:5:9) at Module._compile (module.js:441:26) at Object. JS (module.js:459:10) at Module.load (module.js:348:31) at Function._load (module.js:308:12 ) at Array. 0 (module.js:479:10) at Eventemitter._tickcallback (node. JS:
Inherit Eventemitter

Most of the time we don't use eventemitter directly, but we inherit it from the object. Including FS, NET, HTTP, as long as the core modules that support event response are Eventemitter subclasses.

Why did you do it? There are two reasons:

First, an object with an entity function implements the semantics of the event, and the listener and the launch should be the method of an object.

Secondly, the object mechanism of JavaScript is based on prototype, supporting partial inheritance, inheriting Eventemitter does not disturb the original inheritance relationship of the object.

Node. js Event

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.