import{Observable}from'rxjs/Observable';import{Subject}from'rxjs/Subject';import{INotifyPropertyChanged}from'./INotifyPropertyChanged';import{PropertyChangedEventArgs}from'./propertyChangedEventArgs';exportclassPublisherimplementsINotifyPropertyChanged{// Singletonprivatestaticreadonly_instance=newPublisher();// Using a Subject in order to allow for multiple subscribers// See: http://reactivex.io/rxjs/manual/overview.html#subjectprivatereadonly_propertyChanged=newSubject<PropertyChangedEventArgs>();privateconstructor(){}staticgetinstance(): Publisher{returnPublisher._instance;}// INotifyPropertyChanged implementationgetpropertyChanged(): Observable<PropertyChangedEventArgs>{returnthis._propertyChanged.asObservable();}//#region Propertiesprivate_someProperty=null;getsomeProperty(): any{returnthis._someProperty;}setsomeProperty(value: any){if(this._someProperty!==value){constoldValue=this._someProperty;this._someProperty=value;// Could be useful to have a name() function, like in C#, e.g. name(this.someProperty)this.onPropertyChanged('someProperty',oldValue);}}//#endregion PropertiesprivateonPropertyChanged(propertyName: string,oldValue?: any): void{// Trigger a call to next() on all subscribersthis._propertyChanged.next(newPropertyChangedEventArgs(propertyName,oldValue));}}
The Subscriber Class
import{Observable}from'rxjs/Observable';import{Subscription}from'rxjs/Subscription';import{PropertyChangedEventArgs}from'./propertyChangedEventArgs';import{Publisher}from'./publisher';constpublisher=Publisher.instance;exportclassSubscriber{// store all subscriptions in order to allow for unsubscribing when neededprivate_subscriptions: Subscription[]=[];constructor(publicname: string){this.subscribeToPublisherEvents();}privatesubscribeToPublisherEvents(): void{constsubscription=publisher.propertyChanged.subscribe(args=>this.publisher_propertyChanged(args));this._subscriptions.push(subscription);// ...more events subscriptions}privateunsubscribeFromPublisherEvents(): void{this._subscriptions.forEach(subscription=>subscription.unsubscribe());this._subscriptions=[];}privatepublisher_propertyChanged(e: PropertyChangedEventArgs): void{console.log(`${this.name}: Publisher's ${e.propertyName} property has changed`+`${e.oldValue ? ` from: ${e.oldValue}` : ''} to: ${publisher[e.propertyName]}`);}}