I'm reading Angular.io guide and in Observables chapter I've encountered this snippet:
Create with custom fromEvent function
function fromEvent(target, eventName) {
return new Observable((observer) => {
const handler = (e) => observer.next(e);
// Add the event handler to the target
target.addEventListener(eventName, handler);
return () => {
// Detach the event handler from the target
target.removeEventListener(eventName, handler);
};
});
}
Use custom fromEvent function
const ESC_KEY = 27;
const nameInput = document.getElementById('name') as HTMLInputElement;
const subscription = fromEvent(nameInput, 'keydown')
.subscribe((e: KeyboardEvent) => {
if (e.keyCode === ESC_KEY) {
nameInput.value = '';
}
});
I'm know that an Observable is an object that use a function(subscriber) to witch an object with methods to handle values pushing is passed(observer).
But in this example I don't figure out how variable 'e' is passed and how execution flow works. Can someone help me to understand it?