Learn from me Nodejs (ii)---node.js event module _javascript Skills

Source: Internet
Author: User
Tags emit event listener

Introduction and information

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

Http://www.infoq.com/cn/articles/tyq-nodejs-event

Events is the most important module of Node.js, the events module provides only one object events. The core of Eventemitter,eventemitter is event firing and event listeners.

Most of the modules in the Node.js are inherited from the event module.

Unlike events on the DOM tree, there is no event bubbling, layer-by-level capture behavior.

Eventemitter supports several event listeners. When the event is launched, the event listener registered to this event is called in turn, and the event arguments are passed as callback function arguments.

How to access:

Copy Code code as follows:

Require (' events ');

Emitter.on (event, listener)

Copy Code code as follows:

/*
Call the events module to get events. Eventemitter objects
*/
var eventemitter = require (' Events '). Eventemitter;
var ee = new Eventemitter ();
/*
Eventemitter.on (event, listener) registers a listener for the event
Parameter 1:event string, event name
Parameter 2: callback function
*/
Ee.on (' some_events ', function (foo, bar) {
Console.log ("1th listener event, parameter foo=" + foo + ", bar=" +bar);
});
Console.log (' first round ');
Ee.emit (' some_events ', ' Wilson ', ' Zhong ');
Console.log (' second round ');
Ee.emit (' some_events ', ' Wilson ', ' Z ');
Eventemitter.on (event, listener) sample source code

Emitter.emit (event, [Arg1], [arg2], [...])

Copy Code code as follows:

var eventemitter = require (' Events '). Eventemitter;
var ee = new Eventemitter ();
Ee.on (' some_events ', function (foo, bar) {
Console.log ("1th listener event, parameter foo=" + foo + ", bar=" +bar);
});
/*
Eventemitter.emit (event, [Arg1], [arg2], [...]) Triggers the specified event
Parameter 1:event string, event name
Parameter 2: Optional parameters, passing in the parameters of the callback function in order
Return value: Does the event have a listener
*/
var issuccess = ee.emit (' some_events ', ' Wilson ', ' Zhong ');
Ee.on (' some_events ', function (foo, bar) {
Console.log ("2nd listener event, parameter foo=" + foo + ", bar=" +bar);
});
Ee.emit (' some_events ', ' Zhong ', ' Wei ');
var isSuccess2 = ee.emit (' other_events ', ' Wilson ', ' Zhong ');
Console.log (issuccess);
Console.log (ISSUCCESS2);
Emitter.emit (event, [Arg1], [arg2], [...]) sample source code

The example performed three triggering event operations, where some_events registered for listening, the emit function returns a true when invoked, and other_events does not register for listening, and the emit function returns a false representation that the event is not listening Of course, you can not control this return value!

Emitter.once (event, listener)

Copy Code code as follows:

var eventemitter = require (' Events '). Eventemitter;
var ee = new Eventemitter ();
/*
Eventemitter.once (event, listener) registers a one-time listener for the event, triggers a post-remove listener
Parameter 1:event string, event name
Parameter 2: callback function
*/
Ee.once (' some_events ', function (foo, bar) {
Console.log ("1th listener event, parameter foo=" + foo + ", bar=" +bar);
});
Console.log (' first round ');
Ee.emit (' some_events ', ' Wilson ', ' Zhong ');
Console.log (' second round ');
var issuccess = ee.emit (' some_events ', ' Wilson ', ' Zhong ');
Console.log (issuccess);
Emitter.once (event, listener) sample source code

From the above example code execution results can be seen, with Emitter.once to some_events register a listener, Call the Emitter.emit trigger in two rounds, and the second round returns false; This means that registering with emitter.once is slightly different from the Emitter.on registration listening in the preceding section,

Emitter.once Registration monitoring is a one-time monitoring, when triggered once, will remove the monitor! Of course, from the name on the more obvious look ^_^!

Emitter.removelistener (event, listener)

First look at a failure of the scene ~ ~ ~

Copy Code code as follows:

var eventemitter = require (' Events '). Eventemitter;
var ee = new Eventemitter ();
Ee.on (' some_events ', function (foo, bar) {
Console.log ("1th listener event, parameter foo=" + foo + ", bar=" +bar);
});
/*
When you see the RemoveListener removal method in the API, think it should be
But the results ^_^!!!!!
*/
Ee.removelistener (' some_events ', function () {
Console.log (' Successful removal of event some_events monitor! ');
});
Console.log (' first round ');
Ee.emit (' some_events ', ' Wilson ', ' Zhong ');
Emitter.removelistener (event, listener) sample failed scenario source code

When I used Emitter.on to some_events registered a monitor, I use Emiiter.removelistener to remove some_events listening, and then call Emitter.emit to trigger, and finally found not according to my imagination in progress! Why, then?

I take it for granted that emiiter.removelistener the second parameter is a callback function, the API should be carefully read AH!!!

Let's look at a successful scene here ~ ~ ~

Copy Code code as follows:

var eventemitter = require (' Events '). Eventemitter;
var ee = new Eventemitter ();
var listener = function (Foo,bar)
{
Console.log ("1th listener event, parameter foo=" + foo + ", bar=" +bar);
}
var listener2= function (Foo,bar)
{
Console.log ("2nd listener event, parameter foo=" + foo + ", bar=" +bar);
}
var listener3= function (Foo,bar)
{
Console.log ("3rd listener event, parameter foo=" + foo + ", bar=" +bar);
}
Ee.on (' some_events ', listener);
Ee.on (' some_events ', listener2);
Ee.on (' some_events ', listener3);
/*
Eventemitter.removelistener (event, listener) removes the listener for the specified event
Note: This listener must be a registered
PS: The previous example to be a failure, a big reason is to ignore the listener, for granted that the name of the event to pass the OK, so the tragedy!
*/
Ee.removelistener (' some_events ', listener);
Ee.removelistener (' some_events ', listener3);
Ee.emit (' some_events ', ' Wilson ', ' Zhong ');
Emitter.removelistener (event, listener) sample successful scenario source code

I use the example to write, to Some_events added three listening, and removed the first and third listening, and finally Emitter.emit trigger some_events, the output is not difficult to find, The first and third monitors that were removed with Emitter.removelistener no longer work,

Take it for granted that the second parameter of the original Emitter.removelistener is the listener to be removed, not the successful callback function ... ^_^!

Emitter.removealllisteners ([Event])

Emitter.removelistener used, but an event can have more than one listener, need to remove all, a removal is obviously not a pleasant approach, not in line with the lazy nature!

Let's experience the convenience that Emitter.removealllisteners brings!

Copy Code code as follows:

var eventemitter = require (' Events '). Eventemitter;
var ee = new Eventemitter ();
var listener = function (Foo,bar)
{
Console.log ("1th listener event, parameter foo=" + foo + ", bar=" +bar);
}
var listener2= function (Foo,bar)
{
Console.log ("2nd listener event, parameter foo=" + foo + ", bar=" +bar);
}
Ee.on (' some_events ', listener);
Ee.on (' some_events ', listener2);
Ee.on (' other_events ', function (Foo,bar)
{
Console.log ("Other monitoring events, Parameters foo=" + foo + ", bar=" +bar);
});
/*
Eventemitter.removealllisteners ([Event]) Remove (batch event) all listeners
Parameter 1: Optional argument, event string, events name
*/
Ee.removealllisteners (' some_events ');
Ee.emit (' some_events ', ' Wilson ', ' Zhong ');
Ee.emit (' other_events ', ' Wilson ', ' Zhong ');
Emitter.removealllisteners incoming Event name parameter sample source code

If you look at the results above, you will find that you have registered two listeners to the some_events; other_events registered a listener; I called Emitter.removealllisteners to pass the Some_events event name;

Finally, using the Emitter.on function to trigger the some_events and other_events two events, finally found that some_events registered two of the monitoring does not exist, and other_events registration of the monitoring still exists;

This means that when Emitter.removealllisteners passes the event name as an argument, all the listening for the name of the incoming event is removed, and no other event listener is affected!

Emitter.removealllisteners can not be transmitted using event name parameters;

Copy Code code as follows:

var eventemitter = require (' Events '). Eventemitter;
var ee = new Eventemitter ();
var listener = function (Foo,bar)
{
Console.log ("1th listener event, parameter foo=" + foo + ", bar=" +bar);
}
var listener2= function (Foo,bar)
{
Console.log ("2nd listener event, parameter foo=" + foo + ", bar=" +bar);
}
Ee.on (' some_events ', listener);
Ee.on (' some_events ', listener2);
Ee.on (' other_events ', function (Foo,bar)
{
Console.log ("Other monitoring events, Parameters foo=" + foo + ", bar=" +bar);
});
/*
Eventemitter.removealllisteners ([Event]) Remove (batch event) all listeners
Parameter 1: Optional argument, event string, events name
*/
Ee.removealllisteners ();
Ee.emit (' some_events ', ' Wilson ', ' Zhong ');
Ee.emit (' other_events ', ' Wilson ', ' Zhong ');
Emitter.removealllisteners not pass parameter sample source code

The sample code is almost the same as the incoming parameter, except that the specified event name is not passed in when the emitter.removealllisteners is invoked;

The results of the operation will find that all some_events and other_events are not present, it will remove all the listening! (More violent methods are generally used carefully ~ ~)

Emitter.listeners (Event)

Copy Code code as follows:

var eventemitter = require (' Events '). Eventemitter;
var ee = new Eventemitter ();
var listener = function (Foo,bar)
{
Console.log ("1th listener event, parameter foo=" + foo + ", bar=" +bar);
}
var listener2= function (Foo,bar)
{
Console.log ("2nd listener event, parameter foo=" + foo + ", bar=" +bar);
}
Ee.on (' some_events ', listener);
Ee.on (' some_events ', listener2);
Ee.on (' other_events ', function (Foo,bar)
{
Console.log ("Other monitoring events, Parameters foo=" + foo + ", bar=" +bar);
});
/*
Eventemitter.listeners (Event)//return listener array for specified event
Parameter 1:event string, event name
*/
var Listenereventsarr = ee.listeners (' some_events ');
Console.log (Listenereventsarr.length)
for (var i = listenereventsarr.length-1 i >= 0; i--) {
Console.log (Listenereventsarr[i]);
};
Emitter.listeners (event) sample source code

Register two listeners for some_events, call emitter.listeners function, pass in Some_events event name, receive function return value;

As you can see from the result, the return value receives a collection of all registered Some_events!

Emitter.setmaxlisteners (N)

An event can add multiple listeners yes, but what is the default maximum value for Nodejs?

Copy Code code as follows:

var eventemitter = require (' Events '). Eventemitter;
var ee = new Eventemitter ();
/*
Add 11 listeners to Eventemitter
*/
for (var i = i >= 0; i--) {
Ee.on (' some_events ', function ()
{
Console.log (' first ' + (i + 1) + ' monitor ');
});
};
Add n Listener Sample source code

In the example above, I used a loop to add 11 listeners to the Some_events, execute the code, find the warning information appearing, and prompt the more detailed, need to use emitter.setmaxlisteners () to promote the limit value

Copy Code code as follows:

var eventemitter = require (' Events '). Eventemitter;
var ee = new Eventemitter ();
/*
Eventemitter.setmaxlisteners (n) sets the maximum listener for Eventemitter
Parameter 1:n number type, maximum number of listeners

When more than 10 listeners are listening, the maximum number of listeners that do not set Eventemitter will prompt:
(node) warning:possible Eventemitter memory leak detected. One by one listeners added.
Use Emitter.setmaxlisteners () to increase limit.
The designer believes that too many listeners may cause a memory leak, so there is a warning
*/
Ee.setmaxlisteners (15);
/*
Add 11 listeners to Eventemitter
*/
for (var i = i >= 0; i--) {
Ee.on (' some_events ', function ()
{
Console.log (' first ' + (i + 1) + ' monitor ');
});
};
Emitter.setmaxlisteners Sample Source code

When I call emitter.setmaxlisteners incoming 15 o'clock, execute code, warning information no longer appears;

The role of Emitter.setmaxlisteners is to Eventemitter set the maximum number of listeners, the feeling is generally not required to set this value, 10 is not enough to use the situation should be relatively few!

The designer thinks too much of the listener can cause a memory leak, and all gives a warning!

Other...

The less you use, the more you don't say.

Eventemitter.defaultmaxlisteners

The Eventemitter.defaultmaxlisteners function is similar to the setmaxlisteners,
Set maximum monitoring for all eventemitter
Setmaxlisteners priority is greater than defaultmaxlisteners

Eventemitter.listenercount (emitter, event)

Returns the number of listeners for a specified event

Special Event Error

Reference from the Node.js Development Guide: Eventemitter defines a special event error that contains the semantics of "error", and we usually emit an error event when we encounter an exception. When the error is launched, Eventemitter stipulates that if there is no response to the listener, Node.js will treat it as an exception, exit the program and print the call stack. We typically set up listeners for objects that emit error events, avoiding the entire program crashing after encountering an error.

Inheritance of events

After the     to Util, then talk about it, interested can have a look at their own http://nodejs.org/api/util.html#util_util_inherits_constructor_ Superconstructor

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.