Last active
December 31, 2016 17:02
-
-
Save valerysntx/ef311a131f3c7e805f42528545124e14 to your computer and use it in GitHub Desktop.
Observable of <T>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface IObserver<T> { | |
Notify(observer:Observer<T>, value:T) | |
} | |
class Observer<T> { | |
action: (T) => any; | |
public Set(value: (T) => T) { | |
this.action = value; | |
}; | |
public Get() { return this.action }; | |
constructor(action: (T) => any) { | |
this.action = action; | |
} | |
} | |
class Observable<T> implements IObserver<T> | |
{ | |
public Computed = (action: Observer<T>) => action.action(() => this.get()) | |
public Notify(observer: Observer<T>, value: T) { | |
observer.action(value) | |
} | |
public notifySubscribersComputed(value:T){ | |
if (this.subscribers!==null) | |
this.subscribers.forEach((observer:Observer<T>) => { | |
this.Notify(observer,value); | |
}) | |
} | |
public Subscribe(watch: Observer<T>) { | |
this.subscribers.push(watch) | |
} | |
get () { | |
return this.value | |
} | |
set(value: T) { | |
this.value = value; | |
this.notifySubscribersComputed(value) | |
} | |
value: T; | |
subscribers: Observer<T> []; | |
constructor(T) { | |
this.value = T; | |
this.subscribers = []; | |
} | |
} | |
window.setTimeout(() => { | |
let observable = new Observable(3); | |
let observer = new Observer((t) => alert('observe changes:' + observable.get())); | |
observable.set(5); | |
observable.set(6); | |
observer.action(observable.get()); | |
}, 1000); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment