Created
November 9, 2013 14:06
-
-
Save andreypopp/7385755 to your computer and use it in GitHub Desktop.
Code for http://andreypopp.com/posts/2013-11-09-recreating-core-async-tutorial-with-es6-generators.html
This file contains 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
<!doctype html> | |
<input id="query" type="text"></input> | |
<button id="search">Search</button> | |
<p id="results"></p> | |
<script src="bundle.js"></script> |
This file contains 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
/** | |
* npm install browserify regeneratorify jsonp gens | |
* ./node_modules/.bin/browserify -t regeneratorify ./index.js > bundle.js | |
*/ | |
var jsonp = require('jsonp'); | |
var gens = require('gens'); | |
function *listen(el, evType) { | |
while (true) | |
yield function(cb) { | |
var fire = function(ev) { | |
el.removeEventListener(evType, fire); | |
cb(null, ev); | |
} | |
el.addEventListener(evType, fire); | |
} | |
} | |
function fetch(url) { | |
return jsonp.bind(null, url); | |
} | |
function render(el, items) { | |
var items = items.map(function(item) { | |
return '<li>' + item + '</li>'; | |
}); | |
el.innerHTML = '<ul>' + items.join(''); + '</ul>'; | |
} | |
function go(gen) { | |
gens(gen)(function(err) { if (err) throw err; }); | |
} | |
go(function*() { | |
var results = document.getElementById('results'); | |
var query = document.getElementById('query'); | |
var clicks = listen(document.getElementById('search'), 'click'); | |
while (true) { | |
yield clicks.next().value; // wait for 'click' event | |
var url = 'http://en.wikipedia.org/w/api.php' + | |
'?action=opensearch&format=json&search=' + | |
encodeURIComponent(query.value); | |
var data = yield fetch(url); | |
render(results, data[1]); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does this still run? I seem to be getting errors on
wrapGenerator.wrap(listen)
something