0

Any idea why Facebook emitter is not working for token.remove() call below:

Console:

$ node main.js
5 10
/Users/carlf/Documents/dev/test/emitter/emit-node.js:21
token.remove();
      ^
TypeError: undefined is not a function

My Code:

var {EventEmitter} = require('./node_modules/emitter');
var emitter = new EventEmitter();

var token = emitter.addListener('event', function(x, y) { console.log(x, y); });

emitter.emit('event', 5, 10);  // Listener prints "5 10".

token.remove();
emitter.emit('event', 9, 11); // nothing is logged
Giant Elk
  • 5,375
  • 9
  • 43
  • 56

2 Answers2

1

That error is telling you the remove is not a function. To remove a listener you need to call the removeListener method of that instance of EventEmitter passing the name of the event and the callback you provided. Try this:

var {EventEmitter} = require('./node_modules/emitter');
var emitter = new EventEmitter();

function handler(x, y) {
  console.log(x,y);
}

emitter.addListener('event', handler);

emitter.emit('event', 5, 10);  // Listener prints "5 10".

emitter.removeListener('event', handler);

emitter.emit('event', 9, 11); // nothing is logged
aray12
  • 1,833
  • 1
  • 16
  • 22
  • removeListener() doesn't show up in a search of the gitHub source. Also, my example with `token.remove()` is right off the Emitter gitHub page, so figure that should work. – Giant Elk Apr 22 '16 at 03:01
  • 1
    @GiantElk If you are trying to fbemitter, you are requiring the wrong module. The first line should be `var {EventEmitter} = require('fbemitter');` since that is the name of the package. You also don't need to include a relative path to node_modules. It will check there anyway. – aray12 Apr 22 '16 at 16:17
0

My mistake was I typed npm install emitter, should of been npm install fbemitter'. What threw me was there were no error messages that made this obvious, looks like the core API calls are same in both packages. At least foraddListener()andemit()`.

Once I checked the version # and github URL in `package.json' I figured this out quick.

Giant Elk
  • 5,375
  • 9
  • 43
  • 56