eventbus-ts
TypeScript icon, indicating that this package has built-in type declarations

1.1.2 • Public • Published

Build Status npm version

TypeScript Event Bus

EventBus written in Typescript. Events are typed!

Installation

npm install eventbus-ts

Usage

Importing EventBus and Event

import {EventBus, Subscribe} from "eventbus-ts";

Creating Events

Create Event(s) with the specified type, i.e, string, number, etc.

class DataEvent extends EventBus.Event<string> {}
class NumEvent extends EventBus.Event<number> {}

Overwrite getData() if you need to custom process your data. Ex:

class DisconnectEvent extends EventBus.Event<string> {
    getData(): string {
        return 'Disconnecting... ' + this.data;
    }
}

Register with EventBus

Register for Events with EventBus.getDefault().register(this).

Use Subscribe Decorator

Subscribe to events using @Subscribe('EVENT_NAME') for example:

@Subscribe('DataEvent')
onDataEvent(datastring) : void {
    /* process data from DataEvent */
}

Usage Sample

class Activity {
    constructor() {
        EventBus.getDefault().register(this);
    }
 
    @Subscribe('DataEvent')
    onDataEvent(data: string) : void {
        /* process data from DataEvent */
    }
 
    @Subscribe('NumEvent')
    onNumEvent(data: number): void {
        /* process data from NumEvent */
    }
}

Posting Events

To send events call the post() method for the Event:

EventBus.getDefault().post(new DataEvent('sync up!'));
EventBus.getDefault().post(new NumEvent(299792458));

License

MIT License

Package Sidebar

Install

npm i eventbus-ts

Weekly Downloads

1

Version

1.1.2

License

MIT

Unpacked Size

10.1 kB

Total Files

12

Last publish

Collaborators

  • polyglot