denolibs / event_emitter

A NodeJS-like EventEmitter for Deno in Typescript.
MIT License
12 stars 3 forks source link

Example could use some simplifying. #2

Closed allain closed 5 years ago

allain commented 5 years ago

The example creates a subclass and then uses a chainable method. Neither of those idead are necessary to use the EventEmitter and obscure its elegance.

I suggest these changes, but I know this subjective so feel free to ignore all of this and close it if you like.

import EventEmitter from 'https://raw.github.com/ozjd/deno_event_emitter/master/mod.ts';

const emitter = new EventEmitter()

emitter.on('event', payload => {
  console.log('event', payload)
})

emitter.emit('event', 'hello world!')
emitter.emit('event', 'hello, again, world!')

And then also give an example of using it as a subclass:

class Collection extends EventEmitter {
  items: object[]

  public constructor() {
    super() 
  }

  public add(item:object) {
    this.items.push(item)
    this.emit('added', item)
  }
}

const c = new Collection()

c.on('added', item => console.log('added', item))

c.add('A')
c.add('B')
realJoshByrnes commented 5 years ago

@allain I always extend it so didn't think about the use case of using it as just an EventEmitter, but definitely seem like a fair thing to add.

It's probably a good idea to add the import statement to both examples instead of just the first. I also think it might be worthwhile changing the default URL to https://deno.land/x/event_emitter/mod.ts (points to the same URL)

The only other suggestion I'd have, is on the final two emit() lines and final two add() lines, adding a comment showing what would be printed to console.

Would you mind submitting a PR, so that you're attributed correctly?