DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 72

The task is to implement the fromEvent observable.

The boilerplate code

function fromEvent(element, eventName, capture = false) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

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)
      }
    }
Enter fullscreen mode Exit fullscreen mode

When there is a subscription, it attaches an event listener.

element.addEventListener(eventName, listener, capture);
Enter fullscreen mode Exit fullscreen mode

When the subscription is unsubscribed, it removes the event listener.

return {
unsubscribe() {
element.removeEventListener(eventName, listener, capture);
}
}
Enter fullscreen mode Exit fullscreen mode

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);
        }
      }
    })
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)