Created
September 10, 2015 15:12
-
-
Save zenparsing/ac5abd3c4f45659b0ba2 to your computer and use it in GitHub Desktop.
Consuming Observables with a Generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { 'use strict'; | |
function consume(observable, gen) { | |
return new Promise((resolve, reject) => { | |
if (typeof gen === "function") { | |
// Prime the generator to accept values | |
gen = gen(); | |
gen.next(); | |
} | |
observable.subscribe({ | |
next(v) { send(v, "next") }, | |
error(e) { send(e, "throw") }, | |
complete(x) { send(x, "return") }, | |
}); | |
function send(v, type) { | |
try { | |
let result = gen[type](v); | |
if (result.done) | |
resolve(result.value); | |
} catch (e) { reject(e) } | |
} | |
}); | |
} | |
function listen(element, eventName, capture) { | |
return new Observable(sink => { | |
let handler = e => sink.next(e); | |
element.addEventListener(eventName, handler, Boolean(capture)); | |
return _=> element.removeEventListener(eventName, handler, Boolean(capture)); | |
}); | |
} | |
let clicks = listen(document.body, "click"); | |
consume(clicks, function*() { | |
let evt; | |
while (evt = yield) | |
console.log(`[Click] ${ evt.x }:${ evt.y }`); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment