eventbus-ts
v1.1.2
Published
EventBus written in Typescript.
Downloads
6
Maintainers
Readme
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(data: string) : 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));