Nodejs event mechanism

Source: Internet
Author: User
Tags emit event listener setinterval

node event mechanism 13 Types of TimersThere are three types of timers in the Nodejs: timeout time, time interval, instant timer1. Time-out: SetTimeout (Callback,delaymilliseconds,[args]) method, such as:
SetTimeout (myfunc,1000);
The settimeout function returns the ID of a timer object that can be passed to cleartimeout () at any time before Delaymilliseconds expires to cancel the time function.
var mytimeout=settimeout (myfunc,1000);... cleartimeout (mytimeout);
2. Time interval
var myinterval=setinterval (myfunc,1000);... clearinterval (myinterval);
3. Instant execution of work by the timerAn instant timer is used to execute immediately after an I/O event's callback function starts executing, but before any time-out or interval events are executed.
var myimmediate=setimmediate (myfunc,1000);... clearimmediate (myimmediate);

Two event transmitters and listeners

how the 1.NodeJS event model works. Nodejs does not perform all the work for each request on each thread, it adds the work to the event queue, and then a separate thread runs an event loop to extract the work. The event loop crawls the topmost entry in the event queue, executes it, and then fetches the next entry. When executing code that is long running or has blocking I/O, it does not call the function directly, but adds the function to the event queue, along with a callback function to be executed after this function completes. When all events in the Nodejs event queue are executed, the Nodejs application terminates.  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: The Net.server object distributes an event every time a new link is available, and the Fs.readstream object distributes an event when the file is opened, and 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 '). blocking I/O stops execution of the current thread and waits for a response until a response is received to continue. Nodejs uses event callbacks to avoid waiting for blocking I/O. The key to an event callback is event polling. 2. Registering and launching Custom node. JS EventsThe event is emitted using an Eventemitter object that is contained in the events module, and the emit (Eventname,[args]) function triggers the EventName event, including any arguments provided.
var Eventemitter = require (' Events '). Eventemitter;     // Introducing the Event module var New Eventemitter ();     // instantiating an event module // registering Events (customer_event) function () {    console.log (new  Date ());}); SetInterval (function() {event.emit (' customer_event ');     // launch (trigger) event }, 500);
Use the on Register event for the Eventemitter object, and then use the object's emit to emit events. 3.EventEmitter IntroductionThe events module provides only one object: events. Eventemitter. The core of Eventemitter is the encapsulation of event launch and event listener functionality.
varEventemitter = require (' Events '). Eventemitter;//Introducing the Event modulevarevent =NewEventemitter ();//instantiating an event module//registering Events (SayHello)Event.on (' SayHello ',function(param1, param2) {Console.log (' Hello1: ', param1, param2);}); //registering the event again (SayHello)Event.on (' SayHello ',function(param1, param2) {Console.log (' Hello2: ', param1, param2);}); Event.emit (' SayHello ', ' guying ', ' 1996 ');//launch (trigger) event (SayHello)
Notice that SayHello this event was 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. 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, Accepts a string event and a callback function listener. 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. Eventemitter.emit (event, [Arg1], [arg2], [...]) launches event, passing several optional parameters to the event listener's parameter table. Eventemitter.removelistener (event, listener) removes a listener for the specified event, listener must be a listener that the event has already registered. emitter.listeners (Event) returns an array of listener functions for this eventemitter.setmaxlisteners (n) sets the maximum number of event listeners for this emitter instance, the default is 10, and the setting of 0 is unlimitedEmitter.removealllisteners (event) removes all listener functions for this eventTo give a simple example: userbean.js
varEvents=require (' Events ');varHttp=require (' http ');functionUserBean () {//instantiating an event model     This. eventemit=Newevents.    Eventemitter ();  This. zhuce=function(req,res) {Console.log (Registry); req[' uname ']= ' AA '; req[' pwd ']= ' BB '; //Triggering Events         This. Eventemit.emit (' zhucesuccess ', ' aa ', ' BB '); },     This. login=function(req,res) {Console.log (Login); Res.write (' User name: ' +req[' uname ']); Res.write (' Password: ' +req[' pwd ']); Res.write (Login); }}module.exports=userbean;
Event.js
varHttp=require (' http ');varUserbean=require ('./userbean ')); Http.createserver (function(request,response) {Response.writehead (200,{' content-type ': ' Text/html;charset=utf-8 '}); if(request.url!== ' Favicon.ico ') {User=NewUserBean (); User.eventEmit.once (' Zhucesuccess ',function(UNAME,PWD) {Response.Write (' Registered success '); Console.log (' Chuan uname ' +uname); Console.log (' Pass pwd ' +pwd);            User.login (Request,response);        Response.End ();        });    User.zhuce (Request,response); }}). Listen (8000); Console.log (' Server running at Http://127.0.0.1:8000/');

4.error EventsEventemitter 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 New events. Eventemitter (); Myevent.emit (new Error (' whoops! '));
The following error is displayed at run time: But if you write this correctly, you will be able to:
var events=require (' Events '); Myevent.on (' Error ', (err) = {    console.log (' whoops! There is an error ');}); Myevent.emit (new Error (' whoops! '));

5. NoteMost 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:1) objects with an entity function implement events that conform to semantics, and the interception and launch of events should be the method of an object. 2) JavaScript's object mechanism is prototype-based, supporting partial inheritance, and inheriting eventemitter does not disrupt the original inheritance relationship of the object. The Events module is the heart of node. js, and many other modules use it to surround the event architecture functionality. Because node. JS is running in a single thread, any synchronization code is blocked, so the event loop is blocked if you have long-running code. In order to write code effectively using node. js, you must carefully consider your own style and follow some simple rules. So, how do you add events to your JavaScript object? You first need to invoke events in the object instance. Eventemitter.call (this) to inherit the Eventemitter function in the object, also need to put events. Eventemitter.prototype is added to the object's prototype, such as:
function myObj () {    Events.EventEmitter.call (this);} Myobj.prototype._proto_=evnets. Eventemitter.prototype;
Then issue the event from the object instance:
var newobj=New  myObj (); Newobj.emit (' someevent ');
To give a simple example:
varEvents = require (' Events ');functionAccount () { This. Balance = 0; Events. Eventemitter.call ( This);  This. Deposit =function(amount) { This. Balance + =amount;  This. Emit (' balancechanged ');    };  This. Withdraw =function(amount) { This. Balance-=amount;  This. Emit (' balancechanged '); };} account.prototype.__proto__=events. Eventemitter.prototype;functiondisplaybalance () {Console.log ("Account balance: $%d", This. balance);}functionCheckoverdraw () {if( This. Balance < 0) {Console.log ("Account overdrawn!!!"); }}functionCheckgoal (ACC, goal) {if(Acc.balance >goal) {Console.log ("Goal achieved!!!"); }}varAccount =NewAccount (); Account.on ("Balancechanged", displaybalance); Account.on ("Balancechanged", Checkoverdraw); Account.on ("Balancechanged",function() {Checkgoal ( This, 1000);}); Account.deposit (220); Account.deposit (320); Account.deposit (600); Account.withdraw (1200);

Nodejs event mechanism

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.