Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
 
const Observable = function(producer) {
  this.subscribe = producer
}
Observable.fromEvent = function(element, event){
  const producer = observer => {
    // create an eventHandler
    const eventHandler = e => {
      observer.next(e)
    }
    // adding the eventlistener
    try {
      element.addEventListener(event, eventHandler)
    } catch(err) {
      observer.error(err)
    }
    // return a function to unsusbcribe
    return {
      unsubscribe() {
        element.removeEventListener(event, eventHandler)
      }
    }
  }
  //create and return a new observable
  return new Observable(producer)
}
 
const observableClick = Observable.fromEvent(document, 'click')
const observer = {
  next(event) { console.log(`X: ${event.clientX}, Y: ${event.clientY}`) },
  error(err) { console.log('Error: ', err) },
  complete() { console.log('Done') }
}
const click$ = observableClick.subscribe(observer)
// unsubscribe after 5 seconds
setTimeout(()=>{
  click$.unsubscribe()
}, 5000)
Output

This bin was created anonymously and its free preview time has expired (learn why). — Get a free unrestricted account

Dismiss x
public
Bin info
anonymouspro
0viewers