Node. js emitter. emit method instructions, node. js Use Cases
Method description:
When an event is triggered, several optional parameters are passed to the parameter table of the event listener.
Syntax:
Copy codeThe Code is as follows:
Emitter. emit (event, [arg1], [arg2], [...])
Receiving parameters:
Event Type
Arg1 ~ Parameters passed by argN (multiple)
Example:
Copy codeThe Code is as follows:
Var events = require ('events ');
Var emitter = new events. EventEmitter ();
Emitter. on ('someevent', function (arg1, arg2 ){
Console. log ('listener1', arg1, arg2 );
})
Emitter. on ('someevent', function (arg1, arg2 ){
Console. log ('listener2', arg1, arg2 );
})
Emitter. emit ('someevent', 'byvoid', 1991 );
Source code:
Copy codeThe Code is as follows:
EventEmitter. prototype. emit = function (type ){
Var er, handler, len, args, I, listeners;
If (! This. _ events)
This. _ events = {};
// If there is no 'error' event listener then throw.
If (type = 'error '){
If (! This. _ events. error |
(Util. isObject (this. _ events. error )&&! This. _ events. error. length )){
Er = arguments [1];
If (this. domain ){
If (! Er) er = new TypeError ('uncaught, unspecified "error" event .');
Er. domainEmitter = this;
Er. domain = this. domain;
Er. domainThrown = false;
This. domain. emit ('error', er );
} Else if (er instanceof Error ){
Throw er; // Unhandled 'error' event
} Else {
Throw TypeError ('uncaught, unspecified "error" event .');
}
Return false;
}
}
Handler = this. _ events [type];
If (util. isUndefined (handler ))
Return false;
If (this. domain & this! = Process)
This. domain. enter ();
If (util. isFunction (handler )){
Switch (arguments. length ){
// Fast cases
Case 1:
Handler. call (this );
Break;
Case 2:
Handler. call (this, arguments [1]);
Break;
Case 3:
Handler. call (this, arguments [1], arguments [2]);
Break;
// Slower
Default:
Len = arguments. length;
Args = new Array (len-1 );
For (I = 1; I <len; I ++)
Args [I-1] = arguments [I];
Handler. apply (this, args );
}
} Else if (util. isObject (handler )){
Len = arguments. length;
Args = new Array (len-1 );
For (I = 1; I <len; I ++)
Args [I-1] = arguments [I];
Listeners = handler. slice ();
Len = listeners. length;
For (I = 0; I <len; I ++)
Listeners [I]. apply (this, args );
}
If (this. domain & this! = Process)
This. domain. exit ();
Return true;
};