The task is to implement the fromEvent observable.
The boilerplate code
function fromEvent(element, eventName, capture = false) {
// your code here
}
The fromEvent Observable listens to a browser event and sends that event to whoever is subscribed. There are 2 types of subscribers: a plain function and an observer object.
const listener = (event) => {
if(typeof handler === 'function') {
handler(event);
} else if(handler && typeof handler.next === "function") {
handler.next(event)
}
}
When there is a subscription, it attaches an event listener.
element.addEventListener(eventName, listener, capture);
When the subscription is unsubscribed, it removes the event listener.
return {
unsubscribe() {
element.removeEventListener(eventName, listener, capture);
}
}
The final code
function fromEvent(element, eventName, capture = false) {
// your code here
return new Observable((handler) => {
const listener = (event) => {
if(typeof handler === 'function') {
handler(event);
} else if(handler && typeof handler.next === "function") {
handler.next(event)
}
}
element.addEventListener(eventName, listener, capture);
return {
unsubscribe() {
element.removeEventListener(eventName, listener, capture);
}
}
})
}
That's all folks!
Top comments (0)