Created
September 1, 2018 22:02
-
-
Save hcastillaq/136efaad54075aa775c4eda670cf50f8 to your computer and use it in GitHub Desktop.
Simple Observable with javascript
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
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