@viscum/eventdeprecated

Typescript event emitter.

Usage no npm install needed!

<script type="module">
  import viscumEvent from 'https://cdn.skypack.dev/@viscum/event';
</script>

README

@viscum/event

TypeScript Build Status Coverage Status Npm Package Info Downloads

综述 | Abstract

Typescript event emitter.

使用typescript实现的事件收发机制.

安装 | Install

npm install @viscum/event --save

使用 | Usage

Global emitter & handlers.

import { Event, on, emit } from '@viscum/event'

// Define event class
class FoobarEvent extends Event('foobar') {
  foo: string = 'foo'
  bar: string = 'bar'
}

// Add handler.
const off = on(FoobarEvent, (evt: FoobarEvent, from?: Emitter) => {
  console.log(`${evt.foo} - ${evt.bar} - ${from ? from.name : 'nobody'}`)
})

class Emitter { name: 'emitter' }
const emitter = new Emitter()

// Emit event.
emit(new FoobarEvent) //=> print 'foo - bar - nobody'

// Emit event from an emitter.
emit(new FoobarEvent, emitter) //=> print 'foo - bar - emitter'

// Remove handler.
off()

HasEventEmitter mixin.

import mix from 'mix-with'
import { HasEventEmitter } from 'mix-with'

class MyEvent extends Event('my') {}

class Base {}

class Foobar extends mix(Base).with(HasEventEmitter) {
  name: string = 'foobar'

  action () : void {
    // Emit event from this.
    this.emit(new MyEvent())
  }
}

const foobar = new Foobar()

// Add handler.
on(MyEvent, (evt: MyEvent, from: Foobar) => {
  console.log(from.name)
})

foobar.action() //=> print 'foobar'