Skip to content

Instantly share code, notes, and snippets.

@kn0ll
Last active December 10, 2015 22:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kn0ll/4506060 to your computer and use it in GitHub Desktop.
Save kn0ll/4506060 to your computer and use it in GitHub Desktop.
a way to reflect keyboard state as a backbone model.
define [
'zepto',
'backbone'
], ($, Backbone) ->
# a singleton backbone.model whose
# attributes represent keyboard state
new class extends Backbone.Model
# bind keyboard events to model state
initialize: ->
# maps keyCode to property name
key = (w) =>
switch w
when 38 then 'up'
# etc...
# returns an event handler who
# sets state based on val and keyCode
set = (val) =>
(e) => @set key(e.which), val
# bind keyup/keydown to model
# property values
$ =>
$doc = $(document)
$doc.bind 'keyup', set(false)
$doc.bind 'keydown', set(true)
Backbone.Model::initialize.apply @, arguments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment