Observer patterns
The Observable pattern is one that allows an object, called subject, to keep track of other objects, called observers, interested in the subject state. When the subject state changes, it notifies its observers about it. The mechanics behind this are really simple.
TypeScript Observable
Let's take a look at the following Observer
/Subject
implementation in pure TypeScript (that is no Angular or framework of any kind, just TypeScript).
First, I defined an Observer
interface that any concrete implementation will have to implement:
export interface Observer{ notify(); }
This interface only defines the notify()
method. This method will be called by the subject (that is the Object
being observed by Observer
) when its state changes.
Then, I have an implementation of this interface, named HumanObserver
:
export class HumanObserver implements Observer{ constructor(private name:string){} notify(){ console.log(this.name, 'Notified'); } }
This...