Let's say I have an object like so (using coffeescript):
class Client
constructor: (socket) ->
@id = socket.id
@socket = socket
# some other initialization here...
Now, any time @socket emits something, I want the client object to mimic it by emitting the same event. I can't think of a better way to do this than to just watch for every single event being emitted by @socket and emitting it manually within the Client class, i.e.:
class Client
constructor: (socket) ->
# ...
@socket.on('disconnection', onDisconnect)
@socket.on('message', onMessage)
onDisconnect: ->
this.emit('disconnection')
onMessage: (data) ->
this.emit('message', data)
I know there has to be a better way, but I'm not sure how to go about it.
Something like this? (Untested.)
class Client
constructor: (socket) ->
# ...
for event in ['disconnect', 'message']
@socket.on(event, => @emit(event, arguments))
Monkey-patch @socket
object emit:
class Client
constructor: (socket) ->
@reEmit(socket)
reEmit: (ee)->
oldEmit = ee.emit
ee.emit = (args...)=>
@emit(args)
oldEmit.apply(ee, args)