Heimdall is a simple and light-weight package that implements the Observer Pattern
$ npm install heimdall-js
or
$ yarn add heimdall-js
You can notify all registered observers in a subject:
import Heimdall from 'heimdall-js';
// First param is just the observer name (used to create the context)
const keyboardListener = Heimdall.subject('keyboard', (notify) => {
function handleKeydown({ key }) {
notify({ key });
}
document.addEventListener('keydown', handleKeydown);
});
keyboardListener.subscribe((data) => console.log(data));
But if you want to notify only one or more specific observers... Yes, you can do it!
In this case, you will need to add a name to your observers, like on the last line of code:
import Heimdall from 'heimdall-js';
const keyboardListener = Heimdall.subject('keyboard', (notify) => {
function handleKeydown({ key }) {
notify({ key }, 'observer1'); // Notify only one observer
// or...
// notify({ key }, ['observer1', 'observer2']); // Notify multiple observers
}
document.addEventListener('keydown', handleKeydown);
});
// Set the observer name as the first param
keyboardListener.subscribe('observer1', (data) => console.log(data));
If you want to unsubscribe a single observer you'll need to name him, but, you can run the ubsubscribeAll
method to remove all observers (named or not).
import Heimdall from 'heimdall-js';
const keyboardListener = Heimdall.subject('keyboard', (notify) => {
function handleKeydown({ key }) {
notify({ key });
}
document.addEventListener('keydown', handleKeydown);
});
keyboardListener.subscribe((data) => console.log(data));
keyboardListener.subscribe('observer2', (data) => console.log(data));
keyboardListener.unsubscribe('observer2');
keyboardListener.unsubscribeAll();
Simple like everything should be!