Skip to content

Instantly share code, notes, and snippets.

@hcastillaq
Created September 1, 2018 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hcastillaq/136efaad54075aa775c4eda670cf50f8 to your computer and use it in GitHub Desktop.
Save hcastillaq/136efaad54075aa775c4eda670cf50f8 to your computer and use it in GitHub Desktop.
Simple Observable with javascript
let _instanceObserver = null;
class Observable{
constructor()
{
if( _instanceObserver == null )
{
_instanceObserver = this;
this.observers = {};
}
return _instanceObserver;
}
subscribe( key, func )
{
if( this.observers[key] == undefined )
{
this.observers[key] = [];
}
func.unsubscribe = () => {
this.unsubscribe(key, func)
}
this.observers[key].push(func);
return func;
}
notify( key, data )
{
this.observers[key].forEach( func => func( data ) );
}
unsubscribe(key, func)
{
this.observers[key] = this.observers[key].filter(observer => {
if( observer !== func )
{
return observer;
}
});
}
}
export default new Observable();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment