Why do we wrap our variables in curly braces, like {EventEmitter} = require 'events'
, when extending a Node.js class?
For example, Trevor Burnham, in his tutorial on Event-Driven CoffeeScript, extends Node's EventEmitter this way:
{EventEmitter} = require 'events'
class Rooster extends EventEmitter
constructor: ->
@on 'wake', -> console.log 'COCKADOODLEDOO!'
(foghorn = new Rooster).emit 'wake' # COCKADOODLEDOO!
This:
is equivalent to this JavaScript:
When you
require 'events'
, you're getting an object back with the module's exports, one of those exports is theEventEmitter
"class". Using{EventEmitter}
is just an idiomatic shortcut for pullingEventEmitter
out of the object thatrequire 'events'
returns; you could also say this:if you prefer. The braced version starts to come in handy when you want to extract more than one part of an object; for example, this:
is like this JavaScript:
The Destructuring Assignment section of the CoffeeScript documentation might make some good reading right about now.