node. JS Tutorial 05-eventemitter (Event Listener/emitter)

Source: Internet
Author: User
Tags emit

Directory:

Objective

Node. JS Event Driver Introduction

Node. js Event

Registering and launching Custom node. JS Events

Eventemitter Introduction

Eventemitter Common APIs

Error Event

Inherit Eventemitter

Objective:

There are too many things to do today. Sorry, everybody.

This article focuses on event-driven in node. js, and there are too many things about the node. JS Event concept.

The main idea of this series of courses is to let everyone start slowly, I also try to write a little easier.

So, in this case, the goal should be to understand node. js event drivers, use registration events, and launch events.

  Other only as the understanding, here on a stroke, if you want to know more, please self-Baidu.

Description of the node. JS Event Driver:

node. JS has a short description on GitHub: evented I/O for V8 Javascript.

In a word, domineering side drain: event-driven I/O based on the V8 engine, node. JS is also known for event-driven, high-throughput performance through asynchronous programming.

  

node. JS can stand out from the many back-end JavaScript technologies that are popular because of the nature of its events.

With rhino, you can see that the back-end JavaScript supported by the Rhino engine is free from the effects of synchronous execution in other languages, resulting in a very significant difference between the back-end programming and front-end programming, which cannot be unified on the programming model.

In front-end programming, events are widely used, with various events on the DOM. After the large-scale application of Ajax, the asynchronous request is more widely recognized, and Ajax is also based on the event mechanism.

In rhino, file reads, and so on, are synchronous operations. In this type of single-threaded programming model, if the synchronization mechanism is not comparable to the maturity of the server-side scripting language such as PHP, performance is not worth the commendable part.

It was not until Ryan Dahl launched node. JS in 2009 that back-end JavaScript came out of its fan game.

The launch of node. JS, I think it's time to change two conditions:

    1. Unified programming model for front-end JavaScript.
    2. Using the event mechanism to exploit the performance bottleneck of the single-threaded programming model with asynchronous IO, JavaScript achieves practical value in the backend.

With the help of the best V8 in the second browser war, node. JS has achieved considerable operational efficiency in just two years and is quickly accepted. This is evident from the popularity of the node. JS Project on GitHub and the number of libraries on NPM.

Node. js Event:

In node. js, all asynchronous I/O operations, when completed, send an event to the event queue.

Many objects in node. JS also distribute events, such as:

1. Net. The Server object distributes an event each time a new link is available;

2. The fs.readstream object will distribute an event when the file is opened;

3 .....

All of the objects that produce events are event . an instance of the Eventemitter (event Listener/emitter). We can access the module through the require ('events') .

Event Module (event. Eventemitter) is a simple implementation of the event listener pattern with AddListener , on , once , RemoveListener , Removealllistener , emit and other basic methods of event monitoring mode implementation.

It is not the same as the events on the front-end DOM tree, because it does not have event bubbling , layer-wise capture, and other events that belong to the DOM, nor Preventdefault (), Stoppropagation (), Stopimmediatepropagation () Methods for handling event delivery.

From another point of view, the event listener pattern is also an event hook mechanism that uses event hooks to export internal data or state to external callers.

Many of the objects in node. js, mostly with black box features, have fewer function points, and if the object is not in the form of an event hook, the middle value or internal state of the objects during operation is not available to us.

This way of using the event hooks allows the programmer to focus on how the component is started and executed, just by focusing on the desired event point.

Review our previous creation of the HTTP server's node. js code, the minor change, the new App.js code is as follows:

var http = require ("http"); function onrequest (Request, Response) {    Console.log ("request received.") );    Response.writehead ($, {"Content-type": "Text/plain"});    Response.Write ("Hello world!" );    Response.End ();} Http.createserver (onrequest). Listen()console.log ("Server has started!");

Then we run "node App.js" and visit the browser to see the effect:

  

  

And when we refresh the page, the server creates a request:

  

  "Analysis: (do not merely this part of the content, only need to know about the characteristics of the event in node. JS-" event polling mechanism "OK.) )】

In this code, we use the function onrequest to encapsulate the processing part of the request. When we start it will immediately output "Server started! ”。 When our browser accesses http://128.0.0.1:88, the message "Request received" is displayed. ”

The main difference between the two code is that the former will be processed partially written in Http.createserver , according to the traditional idea, after starting the server, encountered this code will go to run, if the running time is very long, resulting in a pause, very inefficient. If the second user requests the server and it is still in service for the first request, then the second request can only answer after the first one is completed, which is the problem of blocking socket IO .

node. JS is asynchronously performing operations on IO through a low-level C + + layer, and when the request is heard, node. JS executes the callback function that you passed as a parameter to the I/O operation function, such as the onrequestabove. The key to this asynchronous operation is based on the event polling mechanism .

On the event polling mechanism, the internal coverage is relatively wide, I will not increase the length of this article. If interested, we can self-Baidu, online has a case to explain.

To register and launch a custom node. js Event:

Now we're going to do this by registering a user-defined event with node. JS and then launching the custom event using node. js.

Step 1: Create a new app.js with the following code:

1 varEventemitter = require (' Events '). Eventemitter;//Introducing the Event module2 3 varevent =NewEventemitter ();//instantiating an event module4 5 //registering Events (customer_event)6Event.on (' Customer_event ',function() { 7Console.log (' Customer_event has been occured: ' +NewDate ()); 8 }); 9 TenSetInterval (function() {  OneEvent.emit (' customer_event ');//launch (trigger) event (Customer_event) A}, 500);

In the above code, we first use require to introduce the Eventemitter (registration/emitter) of the event module.

We then instantiate the Eventemitter object and deposit it into the local variable event.

We then use the event object's on function to register a custom event named "Customer_event", and the event's action is to output a piece of information.

Finally, we use the SetInterval function, which invokes the emit function of the event object every 500ms loop to emit (trigger) Our custom "Customer_event" event.

  Step 2: Run "node App.js" with the following effect:

This should be very well understood.

So far, we know: Use the Eventemitter object's on register event, and then use the object's emit to emit events.

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.

Let's go straight to the example. Look at the side and say.

  Step 1: Create a new app.js main program with the following code:

1 varEventemitter = require (' Events '). Eventemitter;//Introducing the Event module2 3 varevent =NewEventemitter ();//instantiating an event module4 5 //registering Events (SayHello)6Event.on (' SayHello ',function(param1, param2) {7Console.log (' Hello1: ', param1, param2); 8 }); 9 Ten //registering the event again (SayHello) OneEvent.on (' SayHello ',function(param1, param2) { AConsole.log (' Hello1: ', param1, param2);  - });  -  theEvent.emit (' SayHello ', ' guying ', ' 1996 ');//launch (trigger) event (SayHello)

In the above code, there are two points worth to introduce is the event parameters, second you may feel that the more awkward is that this event registered two times!

Each event of Eventemitter is comprised of an event name and several parameters . The event name 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.

  Step 2: Run "node App.js" and perform the following:

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 commonly used 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 ('error'

The following error is displayed at run time:

node. JS:201 ThrowE//Process.nexttick error, or ' Error ' event on first tick^Error:uncaught, unspecified'Error' Event. At Eventemitter.emit (events.js: -: the) at Object.<anonymous> (/home/byvoid/error.js:5:9) at Module._compile (module.js:441: -) at Object. JS (module.js:459:Ten) at Module.load (module.js:348: to) at Function._load (module.js:308: A) at Array.0(Module.js:479:Ten) at Eventemitter._tickcallback (node. JS:192: +)

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 Tutorial 05-eventemitter (Event Listener/emitter)

Related Article

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.