Created
November 4, 2013 01:02
-
-
Save chrisdickinson/7296642 to your computer and use it in GitHub Desktop.
backing code for examples.
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
// transform an element + eventName into | |
// a stream of those DOMEvents over time. | |
function events(element, eventName, selector) { | |
var lastEvent | |
, nextRead | |
element.on(eventName, selector, onevent) | |
return {read: read} | |
function onevent(ev) { | |
lastEvent = ev | |
check() | |
} | |
function read(emit) { | |
nextRead = emit | |
check() | |
} | |
function check() { | |
if(lastEvent && nextRead) { | |
var ev = lastEvent | |
, cb = nextRead | |
lastEvent = nextRead = null | |
cb(null, ev) | |
} | |
} | |
} | |
// transform a stream of DOMEvents over | |
// time into a stream of the DOMEvent's target's | |
// value over time. | |
function values(inputStream) { | |
return {read: read} | |
function read(emit) { | |
inputStream.read(function(error, ev) { | |
if(err) { | |
emit(err) | |
} else { | |
emit(null, ev.currentTarget.value) | |
} | |
}) | |
} | |
} | |
// create a stream representing application states | |
// over time. | |
function app(initialState) { | |
var state = JSON.parse(JSON.stringify(initialState || {})) | |
, pendingRead | |
, pendingSend | |
return {listen: listen, read: read} | |
function listen(onAttribute, inputStream) { | |
inputStream.read(function(err, value) { | |
state[onAttribute] = value | |
pendingSend = state | |
check() | |
// set the listener up again for the next | |
// incoming event! | |
listen(onAttribute, inputStream) | |
}) | |
} | |
function read(emit) { | |
pendingRead = emit | |
check() | |
} | |
function check() { | |
var outgoing, cb | |
if(pendingRead && pendingSend) { | |
cb = pendingRead | |
outgoing = pendingSend | |
pendingRead = pendingSend = null | |
cb(null, pendingSend) | |
} | |
} | |
} | |
function debounce(inputStream) { | |
return {read: read} | |
function read(emit) { | |
var done = false | |
, sync | |
do { | |
sync = false | |
inputStream.read(function(err, state) { | |
if(done) { | |
emit(state) | |
} | |
sync = true | |
}) | |
} while(sync) | |
done = true | |
} | |
} | |
function template(path, inputStream) { | |
var render = Handlebars.compile($('script[id="' + path + '"]')) | |
return {read: read} | |
function read(emit) { | |
inputStream.read(function(err, state) { | |
emit(null, render(state)) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment