I'm trying to write a library which can be used in Node.js or on the client-side.
I'm running into two issues:
I can't seem to export it correctly. I'm using this doc.
MyClass = exports? and exports or @MyClass = {}
doesn't seem to work, so I split up the files for now.The library emits events; I'm hoping someone can clarify my confusion on how to do this more simply. Follow with me below :)
Node.js:
Library:
{EventEmitter} = require 'events'
class MyClass extends EventEmitter
emitSomething: (key, data) ->
@emit key, data
module.exports = MyClass
Required:
MyClass = require 'myclass'
myClass = new MyClass()
myClass.on 'someevent', (data) ->
console.log data
# Bare with not using `emit` directly.
data =
key: 'value'
myClass.emitSomething 'someevent', data
Client-side
EventEmitter is included.
class MyClass extends EventEmitter
emitSomething: (key, data) ->
@trigger key, [ data ] # That's stupid.
The library file is included in a script and somewhere I do:
myClass = new MyClass()
myClass.on 'someevent', (data) ->
console.log data
data =
key: 'value'
myClass.emitSomething 'someevent', data
Client-side
Backbone.js/Underscore.js are included (not the EventEmitter library above).
class MyClass
constructor: () ->
_.extend @, Backbone.Events
emitSomething: (key, data) ->
@trigger key, data # Notice the difference.
The library file is included in a script and somewhere I do:
myClass = new MyClass()
myClass.on 'someevent', (data) ->
console.log data
data =
key: 'value'
myClass.emitSomething 'someevent', data
So, uh, what's the best way to write a library that emits events for both Node and the browser? The EventEmitter library seemed to conflict with Backbone when I had them both included (it needs to work on Node, and with or without Backbone). There's got to be a simpler solution!