"Turn" Nodejs learning Note (iii)---event module

Source: Internet
Author: User

Directory
    • Introduction and information
    • Common functions of events and their use
      • Emitter.on (event, listener)
      • Emitter.emit (event, [Arg1], [arg2], [...])
      • Emitter.once (event, listener)
      • Emitter.removelistener (event, listener)
      • Emitter.removealllisteners ([Event])
      • Emitter.listeners (Event)
      • Emitter.setmaxlisteners (N)
      • Other...
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, and theEvents module provides only one object, events. The core of Eventemitter,eventemitter is event launch and event listener.

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

Unlike events on the DOM tree, there is no event bubbling, layer-wise capture, and so on.

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.

How to access:

Require (' events ');
Emitter.on (event, listener)

/*    Call the events module to get events. Eventemitter object */var eventemitter = require (' Events '). Eventemitter;   var ee = new Eventemitter ();/*    Eventemitter.on (event, listener) registers a listener    parameter 1:event string for the event  , 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 ');
Emitter.emit (event, [Arg1], [arg2], [...])

Emitter.emit (event, [Arg1], [arg2], [...]) sample source code

The example has three trigger event actions, where some_events registers for listening, the emit function returns a true when called, and Other_events does not register the listener, and the emit function returns a false indicating that the event is not listening And, of course, you can use the return value without the control!

Emitter.once (event, listener)

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, Two rounds of call Emitter.emit Trigger, the second round will return false, this means that the emitter.once registered with the listener and the Emitter.on registered with the previous listener slightly different,

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

Emitter.removelistener (event, listener)

first look at a failed scene ~ ~ ~

Emitter.removelistener (event, listener) sample failure scenario source code

When I used Emitter.on to some_events registered a listener, I use Emiiter.removelistener to remove the some_events, and then call Emitter.emit to trigger, and finally found not as I imagined in progress! Why is it?

I take it for granted that the second parameter of Emiiter.removelistener is a callback function, the API is to be careful to see clearly AH!!!

Let's take a look at the successful scene below.

Emitter.removelistener (event, Listener) example success Scenario source code

I use the example of the wording, 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 taps removed with Emitter.removelistener no longer work,

Take it for granted that the second parameter of Emitter.removelistener is the listener to remove, not the callback function after the successful removal ... ^_^!

Emitter.removealllisteners ([Event])

Emitter.removelistener used, but an event can have multiple listening, need to remove all, one by one removed obviously not pleasant practice, not in line with the lazy nature!

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

emitter.removealllisteners Incoming Event name parameter sample source code

Look at the above execution results, you will find to some_events registered two listeners, to other_events registered a listener; I call 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, and finally found that the some_events registration of the two listeners do not exist, and other_events registration of the monitoring still exists;

This means that when the Emitter.removealllisteners event name is used as a parameter, all listening for the incoming event name is removed without affecting the other event listener!

Emitter.removealllisteners can not pass event name parameters; direct execution

emitter.removealllisteners Non-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 called;

Running results will reveal that all some_events and other_events are not present, and it will remove all listening! (More violent methods are generally used with caution ~ ~)

Emitter.listeners (Event)

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 results, the return value receives a collection of all registered listeners for Some_events!

Emitter.setmaxlisteners (N)

One event can add more than one listener yes, but what is the default maximum value of Nodejs?

Add n Listener sample source code

In the above example, I used a loop to add 11 listeners to some_events, execute the code, find the warning information appears, and the details of the hint, need to use emitter.setmaxlisteners () to increase the limit value

emitter.setmaxlisteners Sample Source code

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

The role of Emitter.setmaxlisteners is to set the maximum number of listeners eventemitter, feel generally do not need to set this value, 10 is not enough to use the situation should be relatively small!

Designers think that too many listeners will cause a memory leak, all of which gives a warning!

Other...

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

Eventemitter.defaultmaxlisteners

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

Eventemitter.listenercount (emitter, event)

Returns the number of listeners for the specified event

Special Event Error

Reference from 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 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.

Inheritance of events

After the return to Util to talk about it, interested can self-see http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor

"Turn" Nodejs learning Note (iii)---event module

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.