Domanda

Is there a way to remove the listeners on a passed in named callback function that are wrapped in an anonymous function?

UPDATE. More complete code examples below.

Here are the details. I've a function that gets passed in a named callback.

Before

function read (message, named_callback ) {

    var named_callback  = named_callback || default_callback
       , message        = message || "Choose: ";

    stdout.write(message);
    stdin.resume();
    stdin.setEncoding('utf8');
    stdin.on('data', named_callback);
    });
};

All the named_callbacks take and prepare a passed in user input (answer).

answer =  answer.trim().toLowerCase(); 

I end up repeating the trimming and lowercasing line everywhere! I wanted to move this step into one place, so tried to prepare the answer before it got passed into the callback. I wrote this:

After

function read (message, named_callback ) {

    var named_callback  = named_callback || default_callback
       , message        = message || "Choose: ";

    stdout.write(message);
    stdin.resume();
    stdin.setEncoding('utf8');
    stdin.on('data', function (answer) {
        answer =  answer.trim().toLowerCase();
        named_callback(answer);
    });
};

However, this results in event listeners not being removed, and they just pile up until the program crashes with too many listeners.

Thank you.

È stato utile?

Soluzione

the problem is probably not where you think it is. with the info you give i would expect you just call the read method everytime, and thats where the tomanylisteners comes into place, because you just everytime append a new 'data' listener. if you change that 'on' to 'once' your application shouldnt crash anymore:

stdin.once('data'...

this of course isnt the solution to your problem, it is just to illustrate where your problem is (its not the trim/tolowercase.

if you show as a little bit more of your code maybe we are able to help you better, but probably your read-method is just unecessary overhead...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top