node.js - Adding listeners in nodeJS if the listener is not already added and listener handler is an anonymous function -


is there way check if listener exist object in node.js? want implement following scenario:

  • get object of db
  • do operation
  • add listeners eg error, result, drain etc if same listener not added [assume operations listener operation same]

i wanted optimize addition of listeners in such way new listeners wont added if try , add existing listener. node documentation says "no checks made see if listener has been added. multiple calls passing same combination of eventname , listener result in listener being added, , called, multiple times."

is there way around it?
[edit]-adding sample code

 connpool.getconnection(function(err, connection) {        var querystr = "some valid sql query";        connection.execute(querystr, data, function(err, rows) {         if (err) {           console.error(err);         }         connection.on('error', function(err){onerr(err,connection);});         stuff         cleanup(connection);     });     })       var onerr = function(err, connection) {       console.error({"error message"});       connection.release();       cleanup(connection);    };     var cleanup = function(conn) {     conn.removelistener('error',onerr);    }; 

connection contain db connection , coming external package.in statement connection.on('error', function(err){onerr(err,connection);}); i'm using anonymous function need pass argument cleanup method. during cleanup dont handler function i'm using anonymous function.

as long keep reference listener when hook it, can check if in array of listeners returned emitter.listeners(eventname).

rough example (i'm sure more efficient)

/**  * created cool.blue on 8/4/2016.  * http://stackoverflow.com/q/38700859/2670182  */ const ee = require('events'); const util = require('util');  var host = new ee();  // set emitter n events const n = 10; const events = array.apply(null, array(n)).map((x, i) => 'event_' + i);  events.foreach(function(e){     host.on(e, function g() {console.log(e)}) });  console.log(util.inspect(host));  // reference 1 of listener functions const target = 'event_3'; var probe = host.listeners(target)[0];  // add method add unique listeners host.onunique = function (type, listener){     var slot = this.listeners(type).find(function(l) {         return l === listener     });      if(slot)         return this;      console.log('adding');     return this.on(type, listener) };  // try add same listener again var count0 = host.listenercount(target); var count1 = host.onunique(target, probe).listenercount(target);  console.log('added ' + (count1 - count0) + ' listeners');   // added 0 listeners console.log(util.inspect(host));  // try add new listener count0 = host.listenercount(target); count1 = host.onunique(target, function h(){ console.log('different cb')}).listenercount(target);  console.log('added ' + (count1 - count0) + ' listeners');   // added 1 listeners console.log(util.inspect(host)); 

in response updated question...

you this...

tl;dr

the basic idea use non-anonymous function listener , pass reference , connection utility functions in outer scope.

const ee = require('events'); const util = require('util');  (function manage(host){      host.name = 'host';     host.release = function(){         console.log('released!')     };      function l(err) {         onerr(err, host, l)     }     l.e = 'error';      host.on('error', l);      if(math.random() > 0.5)         host.emit('error', new error('oops!'));      if(l.e)         cleanup(host, l, 'manage');  })(new ee());  function onerr(e, h, l) {     console.error(`\n${h.name}: ${e.message}`);     h.release();     cleanup(h, l, 'onerror') }  function cleanup(h, l, context){     console.log('\n\x1b[33m' + context + '\n'         + 'before:\t' + h._eventscount + '\x1b[0m\n' + util.inspect(h));     h.removelistener(l.e, l);     console.log('\n\x1b[33mafter:\t' + h._eventscount + '\x1b[0m\n' + util.inspect(h));     delete l.e } 

the iife simulate situation there no reference host (connection) in outer scope.


Comments