node. JS Eventemitter Sending and receiving events

Source: Internet
Author: User
Tags emit stack trace

Eventemitter is part of the Nodejs core. Many Nodejs objects inherit from Eventemitter and are used to handle events and callbacks. API Document Address:

Http://nodejs.org/api/events.html#events_class_events_eventemitter

Event:

Many objects in Node emit events: A net.Server emits the event each time a peer connects to it, a fs.readStream emits an event When the file is opened. All objects which emit events is instances events.EventEmitter of. You can access the This module by doing:require("events");

Typically, event names is represented by a camel-cased string, however, there aren ' t all strict restrictions on that, as Any string would be accepted.

Functions can then was attached to objects, and to being executed when a event is emitted. These functions is calledlisteners. Inside a listener function, refers to the, the this EventEmitter listener is attached to.

Class:events. eventemitter#

To access the Eventemitter class, require(‘events‘).EventEmitter .

When EventEmitter a instance experiences an error, the typical action was to emit an ‘error‘ event. Error events is treated as a special case in node. If There is no listener for it, then the default action was to print a stack trace and exit of the program.

All eventemitters emit the event when ‘newListener‘ new listeners was added and when ‘removeListener‘ a listener was removed.

Emitter.addlistener (event, listener) #emitter. On (event, listener) #

Adds a listener to the end of the listeners array for the specified event.

server.on(‘connection‘, function (stream) { console.log(‘someone connected!‘);});

Returns emitter, so calls can be chained.

Emitter.once (event, listener) #

Adds a one time listener for the event. This listener was invoked only the next time the event was fired, after which it was removed.

server.once(‘connection‘, function (stream) { console.log(‘Ah, we have our first user!‘);});

Returns emitter, so calls can be chained.

Emitter.removelistener (event, listener) #

Remove a listener from the listener array for the specified event. Caution: Changes array indices in the listener array behind the listener.

 var callback = function (Stream) {console.log ( ' someone connected! ' };server. On ( ' connection '  callback //... server. Removelistener ( ' connection '  callback< Span class= "Sh_symbol");              

Returns emitter, so calls can be chained.

Emitter.removealllisteners ([Event]) #

Removes all listeners, or those of the specified event. It's not a good idea to remove listeners this were added elsewhere in the code and especially when it's on an emitter that yo U didn ' t create (e.g. sockets or file streams).

Returns emitter, so calls can be chained.

Emitter.setmaxlisteners (N) #

By default Eventemitters would print a warning if more than listeners is added for a particular event. This is a useful default which helps finding memory leaks. Obviously not all emitters should is limited to 10. This function allows the is increased. Set to zero for unlimited.

Emitter.listeners (Event) #

Returns an array of listeners for the specified event.

Server.On ( ' connection '  function  (Stream) {consolelog ( ' someone connected! ' }. Log (Util. Inspect (Server. Listeners ' connection ' //[[Function]]             
Emitter.emit (event, [Arg1], [arg2], [...]) #

Execute each of the listeners in order with the supplied arguments.

Returns true If event had listeners, false otherwise.

Class Method:EventEmitter.listenerCount (Emitter, event) #

Return the number of listeners for a given event.

Event: ' Newlistener ' #
    • eventString the event name
    • listenerfunction The event handler function

This event was emitted any time someone adds a new listener. It is unspecified if are in the listener list returned by emitter.listeners(event) .

Event: ' RemoveListener ' #
    • eventString the event name
    • listenerfunction The event handler function

This event was emitted any time someone removes a listener. It is unspecified if are in the listener list returned by emitter.listeners(event) .

/*Eventemitter sends and receives events Httpserver and HttpClient classes, both of which inherit from Eventemitter Eventemitter are defined in the events module of node, Using the Eventemitter class directly requires declaring require (' events '), otherwise you do not have to explicitly declare require (' events '), because many objects in node do not need you to call require (' events ') You'll use Eventemitter .*/varEvents = require (' Events ');varUtil = require (' util '));functionPulser () {events. Eventemitter.call ( This);} Util.inherits (Pulser, events. Eventemitter); Pulser.prototype.start=function(){    varSelf = This;  This. id = setinterval (function() {Util.log (' >>>>pulse '); Self.emit (' Pulse '); Util.log (' <<<<pulse '); }, 1000);}//defines a class pulser, which is inherited from Eventemitter by Util.inherits, which is the function of sending a timed event to all listeners every second. //The Start method uses the SetInterval function to periodically repeat the callback function and call the emit method to send the Pulse event to each listener//using the Pulser object/*creates a Pulser object and processes its pulse event, executing pulser.on (' pulse ' ...) Establish contact for pulse events and callback functions*/varPulser =NewPulser ();p Ulser.on (' Pulse ',function() {Util.log (' Pulse received ');}); Pulser.start ();//objects use the Emit function to send events, and all listeners registered to the corresponding event can receive events;//registers the listener by calling the. On method, which is the event name and receives the event with a callback function//Usually, there is some data that needs to be sent along with the event Self.emit (' EventName ', data1, data2, ...);//emitter.on (' EventName ', function (data1, data2,..) {       //actions after receiving an event// });

node. JS Eventemitter Sending and receiving events

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.