0

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:

  1. 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.

  2. 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!

4

1 回答 1

2

您应该考虑使用 browserify,它可以让您简单地使用 MyClass 模块客户端,因为它包含一个版本的 nodecore 事件。

所以客户端:

MyClass = require('./myclass')
myClass = new MyClass()

http://browserify.org/

https://github.com/substack/coffeeify

于 2013-04-17T23:42:26.653 回答