Created
December 4, 2015 03:35
-
-
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...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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); |
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.
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
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
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."