Skip to content

Instantly share code, notes, and snippets.

@micdenny
Forked from KeithGillette/MessageService.ts
Last active January 24, 2018 18:23
Show Gist options
  • Save micdenny/0cf99f53bdc83e7cce6b2296da24a000 to your computer and use it in GitHub Desktop.
Save micdenny/0cf99f53bdc83e7cce6b2296da24a000 to your computer and use it in GitHub Desktop.
Simple AngularJS 1.X TypeScript Message Bus
import * as angular from 'angular';
import { Observable, Subject, Subscription } from '@reactivex/rxjs';
export interface Message {
channel: Function;
content: any;
}
/**
* @description AngularJS service singleton implementing simple publish/subscribe message bus to provide decoupled communication of commands & events
*/
export class MessageService {
private _message$: Subject<Message>
constructor() {
this._message$ = new Subject<Message>();
}
public publish<T>(messageInstance: T): void { // Flux: 'publish' = 'dispatch', 'channel' = 'action'
const channel: Function = messageInstance.constructor;
this._message$.next({ 'channel': channel, 'content': messageInstance });
}
public of<T>(messageClass: { new (...args: any[]): T }): Observable<T> { // Flux: 'subscribe' = 'on'
const channel = messageClass;
return this._message$.filter((message) => { return message.channel === channel }).map((message) => { return message.content; });
}
}
angular.module('TaskTrainApp')
.service('MessageService', MessageService);
// Just some sample message classes
/**
* @description encapsulation class for messages sent to the MessageService message bus to provide channel type and TypeScript typing
*/
export class UserNotificationMessage {
constructor(
public message: string,
public notificationType?: NotificationType,
public options?: any,
public notifier?: any
) { }
}
export type NotificationType = 'success' | 'info' | 'warning' | 'danger' | 'error';
/**
* @description base class for all DomainModelService UPDATE operations
*/
abstract class DomainModelUpdateRequestMessage {
constructor(
public id: string,
public domainModelObject: domain.IDomainModel,
public newValue?: any,
public oldValue?: any,
) { }
}
/**
* @description encapsulation class for messages sent to the MessageService message bus to provide TypeScript typing
*/
export class ProcedureUpdateNameOnClientRequestMessage extends DomainModelUpdateRequestMessage {
public domainModelObject: domain.IProcedure;
}
import * as message from './MessageServiceClasses';
// assume MessageService is injected
this.MessageService.publish(new message.ProcedureUpdateNameOnClientRequestMessage(this.id, this, newValue, this._name));
import * as message from './MessageServiceClasses';
// assume MessageService is injected & some callback handlers defined to pass in
this.MessageService.of(message.ProcedureUpdateNameOnClientRequestMessage)
.subscribe(this.updateNameOnClientRequestHandle.bind(this), this._genericErrorHandler.bind(this))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment