Skip to content

Instantly share code, notes, and snippets.

@Trott
Created December 4, 2015 03:35
Show Gist options
  • Save Trott/a865746d08814af087b7 to your computer and use it in GitHub Desktop.
Save Trott/a865746d08814af087b7 to your computer and use it in GitHub Desktop.
Can Node use Symbols for the name of an Event? I'd say yep...
'use strict';
const util = require('util');
const EventEmitter = require('events');
function MyEventEmitter() {
EventEmitter.call(this);
}
// Inherit functions from `EventEmitter`'s prototype
util.inherits(MyEventEmitter, EventEmitter);
const foo = new MyEventEmitter();
const symbol = Symbol('Hi, Bengie! Err... I mean, Bryan!');
foo.on(symbol, function () { console.log('symbol event fired!'); })
foo.emit(symbol);
@bengl
Copy link

bengl commented Dec 4, 2015

const ee = new (require('events').EventEmitter)()

const handler = () => console.log('hi @trott!')

ee.on(Symbol.for('@trott'), handler)
ee.emit(Symbol.for('@trott')) // hi @trott!

ee.on(42, handler)
ee.emit(42) // hi @trott!

ee.on('hi', handler)
ee.emit('hi') // hi @trott!

ee.on({}, handler)
ee.emit({}) // hi @trott!

I suppose a doc change might be in order here. Along the lines of "Anything that's a valid property name (or coerces to one) is a valid event name."

@Trott
Copy link
Author

Trott commented Dec 4, 2015

I think Symbols are still special, at least based on observation and not looking at the implementation.

ee.emit(42) and ee.emit('42') seem to behave the same. They are interchangeable.

But ee.emit('Symbol(42)') and ee.emit(Symbol(42)) are not interchangeable.

Symbol(42) != Symbol(42) and ee.on(Symbol(42), handler); ee.emit(Symbol(42)); will not trigger the handle.

@bengl
Copy link

bengl commented Dec 4, 2015

Yep, but not any more special than they would be as property names:

let sym = Symbol(2)
let x = {'2': 42, [sym]: 43}

x[2] == 42

x['2'] == 42

x[sym] == 43

x[Symbol(2)] == undefined

@kessler
Copy link

kessler commented May 3, 2018

3 years later...

let event = Symbol('event')
let EventEmitter = require('events')
let x = new EventEmitter()
x.on(event, console.log)

console.log('emit with symbol:')
x.emit(event, 1)

console.log('emit with string:')
x.emit('event', 1)

console.log('emit with symbol.toString:')
x.emit(event.toString(), 1)

The output will be:

emit with symbol:
1
emit with string:
emit with symbol.toString:

So maybe symbols are not coerced into strings after all / anymore?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment