Skip to content

Instantly share code, notes, and snippets.

@sethvincent
Last active March 10, 2016 22:24
Show Gist options
  • Save sethvincent/38bf33ab9bfe46f32443 to your computer and use it in GitHub Desktop.
Save sethvincent/38bf33ab9bfe46f32443 to your computer and use it in GitHub Desktop.
idea for controller api
var keyboard = require('controller-keyboard')
var gameState = {
input: {}
}
keyboard.subscribe(function (action, active) {
// active is the current inputs that are active
// this is triggered every time the state of a key has changed
// maybe we would do something like this to the game state:
gameState.input['keyboard'] = active
// except this part could be done with immutable, redux-like dispatches
// action looks like this:
{
type: 'on' || 'off',
value: 'value representing the input',
event: // original event, browser keyboard event, for instance
}
})
var vkey = require('vkey')
module.exports = function createKeyboardController (options) {
var listener = function () {}
var active = {}
document.addactionListener('keydown', function (e) {
var value = vkey[e.keyCode]
active[value] = true
var action = {
type: 'on',
value: value,
event: e
}
listener(action, active)
}, false)
document.addactionListener('keyup', function (e) {
var value = vkey[e.keyCode]
delete active[value]
var action = {
type: 'off',
value: value,
event: e
}
listener(action, active)
}, false)
return {
subscribe: function (cb) {
listener = cb
}
}
}
@sethvincent
Copy link
Author

I wonder if it would be easier to have action creators that do things like

move(state.position, action.keys)

And then dispatch the result. That way the reducer stays as simple as possible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment