Skip to content

Instantly share code, notes, and snippets.

@lsm
Created March 16, 2015 23:34
Show Gist options
  • Save lsm/8167d7a2f2f39ad586d1 to your computer and use it in GitHub Desktop.
Save lsm/8167d7a2f2f39ad586d1 to your computer and use it in GitHub Desktop.
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