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>
  <button id="increase">Moar</button>
</body>
</html>
 
// http://nick.balestra.ch/2016/Understanding-the-observable-type/
const Observable = function(producer) {
  this.subscribe = producer
}
// http://nick.balestra.ch/2016/creating-observables/
Observable.fromEvent = function(element, event){
  const producer = observer => {
    const eventHandler = e => {
      observer.next(e)
    }
    try {
      element.addEventListener(event, eventHandler)
    } catch(err) {
      observer.error(err)
    }
    return {
      unsubscribe() {
        element.removeEventListener(event, eventHandler)
      }
    }
  }
  return new Observable(producer)
}
Observable.prototype.map = function(transformation){
  const originalProducer = this.subscribe;
  const newProducer = function(observer){
    originalProducer({
      next (value) {observer.next(transformation(value))},
      error (err) {observer.error(err)},
      complete () {observer.complete()}
    })
  }
  return new Observable(newProducer)
}
Observable.prototype.mapTo = function(value){
  return this.map(() => value)
}
const increaseButton  = document.getElementById('increase')
const action$ = Observable.fromEvent(increaseButton, 'click')
  .mapTo({ type: 'INCREASE'})
const click$ = action$.subscribe({
  next(value) { console.log(value) },
  error(err) { console.log('Error: ', err) },
  complete() { console.log('Done') }
})
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