SimpleSubject
Subscribe, notify, unsubscribe
A simple, no-frills subject-observer implementation written in TypeScript.
Installation
> npm install simple-subject
From source
> git clone git@github.com:jabney/simple-subject.git > cd simple-subject > npm install > npm run build
Usage
// Import the classconst SimpleSubject = // Create an instanceconst subject = // Subscribe and define a notification callbackconst observer1 = subject // Subscribe and define a notification callbackconst observer2 = subject // Subscribe and define a notification callbackconst observer3 = subject // Notify all observerssubject // Unsubscribe observersfor const observer of observer1 observer2 observer3 ovserver
Output:
subscriber 0: {message: "notified"}
subscriber 1: {message: "notified"}
subscriber 2: {message: "notified"}
Using TypeScript
If your tsconfig.json
is set up to use commonjs modules, e.g., "module": "commonjs"
, you can use require
:
const subject:SimpleSubject =
However this doesn't work when using ES2015 modules, e.g., "module": "es2015"
. In this case, use the TypeScript source:
const subject:SimpleSubject =
SimpleSubject
supports generic notation for specifying the type of the data payload.
interface IMessage from: string with: string const doubleOh: SimpleSubject<IMessage> = const mi6:ISubscriptionToken = doubleOh const message:IMessage = from: 'Russia' with: 'Love' doubleOh mi6
Output:
{ from: "Russia", with: "Love" }