Reputation: 105
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?
Upvotes: 1
Views: 2618
Reputation: 29335
maybe clearer like this:
function fromEvent(target, eventName) {
return new Observable((observer) => {
// Add the event handler to the target
target.addEventListener(eventName, (e) => {
// when event listener fires, call next on the observer with the event
// this sends the event to subscribers of the observable
observer.next(e)
});
return () => {
// clearly this doesn't work anymore as you have no reference to the handler
// so this creates a memory leak
// target.removeEventListener(eventName, handler);
};
});
}
Upvotes: 1
Reputation: 137
The parameter 'e' is called out of scope of this example in a sense. It is the parameter for the function named 'handler'. When 'handler' is used by another function, in this case addEventListener or removeEventListener, it will at that point be supplied with a parameter, which 'e' will represent.
Upvotes: 0
Reputation: 11468
This is ES6 syntax.
// ES6
const handler = (e) => observer.next(e);
// Equals to
const handler = function(e) {
return observer.next
}
document.addEventListener
accepts the name of the event, and the event itself:
target.addEventListener(type, listener[, options]);
target.addEventListener(type, listener[, useCapture]);
target.addEventListener(type, listener[, useCapture, wantsUntrusted ]); // Gecko/Mozilla only
type
A case-sensitive string representing the event type to listen for.
listener
The object which receives a notification (an object that implements the Event interface) when an event of the specified type occurs. This must be an object implementing the EventListener interface, or a JavaScript function. See The event listener callback for details on the callback itself.
You can read more about it in MDN web docs
Upvotes: 0