Skip to content

Instantly share code, notes, and snippets.

@VineetKumarKushwaha
Last active June 27, 2020 09:21
Show Gist options
  • Save VineetKumarKushwaha/66db311d8f655e1eba3660dd3e704563 to your computer and use it in GitHub Desktop.
Save VineetKumarKushwaha/66db311d8f655e1eba3660dd3e704563 to your computer and use it in GitHub Desktop.
Observer pattern
const makeObservable = (fn) => {
const observers = new Map();
const register = (observer) => observers.set(observer, observer);
const deRegister = (observer) => observers.delete(observer)
const notify = (value) => observers.forEach(observer => observer && observer(value));
fn(notify);
return { register, deRegister };
}
/*
const messageObservable = makeObservable((notify) => {
setInterval(() => notify(Math.floor(Math.random() * 100)), 1000)
});
messageObservable.register((value) => console.log("from first", value))
messageObservable.register((value) => console.log("from first", value))
const fn1 = (s) => console.log("hello", s);
messageObservable.register(fn1)
*/
@VineetKumarKushwaha
Copy link
Author

VineetKumarKushwaha commented Jun 27, 2020

“The observer pattern is a software design pattern in which an object, called the subject(observable), maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.” — Wikipedia definition

@VineetKumarKushwaha
Copy link
Author

Drawing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment