Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compare stream style
$(function() {
var spaceKeyCode = 32;
//-----------------------------------------
var stream = require('dim')();
var model = {};
stream
.setDep('user', model, '*^')
.setDep('error', 'errorName1')
.on('keyup', document)
.on('keydown', document)
.pipe(setKeyCode, [null, 'streamName'])
.filter(isSpaceKey, 'keyCode')
.pipe(changeText, ['streamName', 'user^getName', 'next'])
.error()
.user();
function isSpaceKey(keyCode) {
return keyCode === spaceKeyCode;
}
function setKeyCode(event) {
this.setDep('keyCode', event.keyCode);
return true;
}
function changeText(streamName, getName, next) {
$('#keyState').text(streamName === 'keydown');
$('#name').text(getName());
getName(function(name) {
$('#name').text(name);
next(null, name);
});
}
//-----------------------------------------
var spaceDown = false;
function updateResult(result) {
$('#keyState').text(spaceDown);
}
$(document).on('keyup', function(event) {
var keyCode = event.keyCode;
if (keyCode === spaceKeyCode) {
spaceDown = false;
updateResult(spaceDown);
}
});
$(document).on('keydown', function(event) {
var keyCode = event.keyCode;
if (keyCode === spaceKeyCode) {
spaceDown = true;
updateResult(spaceDown);
}
});
});
$(function() {
// allKeyUps :: Observable KeyEvent
var allKeyUps = $(document).asEventStream("keyup")
var allKeyDowns = $(document).asEventStream("keydown")
// always :: a -> (b -> a)
function always(value) {
return function(_) {
return value
}
}
// keyCodeIs :: Int -> (KeyEvent -> Bool)
function keyCodeIs(keyCode) {
return function(event) {
return event.keyCode == keyCode
}
}
// keyUps :: Int -> Observable KeyEvent
function keyUps(keyCode) {
return allKeyUps.filter(keyCodeIs(keyCode))
}
function keyDowns(keyCode) {
return allKeyDowns.filter(keyCodeIs(keyCode))
}
// keyState :: Int -> Observable Bool
function keyState(keyCode) {
return keyDowns(keyCode).map(always(true))
.merge(keyUps(keyCode).map(always(false)))
.toProperty(false)
}
keyState(32).onValue(function(spaceDown) {
$('#keyState').text(spaceDown)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment