Created
March 19, 2014 20:52
-
-
Save aubinlrx/9650965 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# Throttled Input event | |
# | |
#= provides throttled:input | |
# | |
#= require jquery | |
# | |
# Delays firing `input` event until user is done typing. | |
# | |
# ### Events | |
# | |
# `throttled:input` | |
# | |
# * **Synchronicity** Async | |
# * **Bubbles** Yes | |
# * **Cancelable** No | |
# * **Target** Field that is receiving input. | |
# | |
# ``` coffeescript | |
# $('input').on 'throttled:input', -> | |
# filterResults $(this).val() | |
# ``` | |
# | |
setup = -> | |
keypressed = false | |
inputed = false | |
timer = null | |
delay = 100 | |
schedule = (target) => | |
clearTimeout timer if timer | |
timer = setTimeout => | |
timer = null | |
event = new $.Event 'throttled:input', {target} | |
$.event.trigger event, null, this, true | |
return | |
, delay | |
return | |
$(this).on 'keydown.throttledInput', -> | |
inputed = false unless keypressed | |
keypressed = true | |
clearTimeout timer if timer | |
return | |
$(this).on 'keyup.throttledInput', (event) -> | |
keypressed = false | |
schedule event.target if inputed | |
inputed = false | |
return | |
$(this).on 'input.throttledInput', (event) -> | |
inputed = true | |
schedule event.target unless keypressed | |
return | |
teardown = -> | |
$(this).off 'keydown.throttledInput' | |
$(this).off 'keyup.throttledInput' | |
$(this).off 'input.throttledInput' | |
$.event.special['throttled:input'] = {setup, teardown} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment