Descripción del método:
Registre un oyente para el evento especificado.
gramática:
La copia del código es la siguiente:
emitor.on (evento, oyente)
emitter.addlistener (evento, oyente)
Recibir parámetros:
Tipo de evento de evento (cadena)
oyente (función) La función de devolución de llamada cuando se activa el evento
ejemplo:
La copia del código es la siguiente:
servidor.on ('conexión', function (stream) {
console.log ('¡Alguien conectado!');
});
Código fuente:
La copia del código es la siguiente:
EventEmitter.prototype.addListener = function (type, oyente) {
var m;
if (! util.Isfunction (oyente))
arrojar typeError ('El oyente debe ser una función');
if (! this._events)
this._events = {};
// Para evitar la recursión en el caso de ese tipo === "NewListener"! Antes
// Agregarlo a los oyentes, primero emita "NewListener".
if (this._events.newlistener)
this.emit ('NewListener', tipo,
Util.Isfunction (Listener.listener)?
oyente.listener: oyente);
if (! this._events [tipo])
// Optimizar el caso de un oyente. No necesito el objeto de matriz adicional.
this._events [type] = oyente;
else if (util.isobject (this._events [type]))
// Si ya tenemos una matriz, solo agregue.
this._events [type] .push (oyente);
demás
// Agregar el segundo elemento, debe cambiar a la matriz.
this._events [type] = [this._events [type], oyente];
// Verifique la fuga del oyente
if (util.isobject (this._events [type]) &&! this._events [type] .Warned) {
var m;
if (! util.isundefined (this._maxListeners)) {
m = this._maxListeners;
} demás {
M = EventEmitter.defaultMaxListeners;
}
if (m && m> 0 && this._events [type] .length> m) {
this._events [type] .warned = true;
console.error ('(nodo) Advertencia: posible memoria EventEmitter' +
'Fuga detectada. %d oyentes agregados. ' +
'Use emitter.setMaxListeners () para aumentar el límite'.
this._events [type] .length);
console.trace ();
}
}
devolver esto;
};