Skip to content

Instantly share code, notes, and snippets.

@glebtv
Created November 13, 2013 21:17
Show Gist options
  • Save glebtv/7456560 to your computer and use it in GitHub Desktop.
Save glebtv/7456560 to your computer and use it in GitHub Desktop.
#! jQuery Ajax Queue - v0.1.2pre - 2013-03-19
#* https://github.com/gnarf37/jquery-ajaxQueue
#* Copyright (c) 2013 Corey Frang; Licensed MIT
(($) ->
# jQuery on an empty object, we are going to use this as our Queue
ajaxQueue = $({})
$.ajaxQueue = (ajaxOpts) ->
# run the actual query
doRequest = (next) ->
jqXHR = $.ajax(ajaxOpts)
jqXHR.done(dfd.resolve).fail(dfd.reject).then next, next
jqXHR = undefined
dfd = $.Deferred()
promise = dfd.promise()
# queue our ajax request
ajaxQueue.queue doRequest
# add the abort method
promise.abort = (statusText) ->
# proxy abort to the jqXHR if it is active
return jqXHR.abort(statusText) if jqXHR
# if there wasn't already a jqXHR we need to remove from queue
queue = ajaxQueue.queue()
index = $.inArray(doRequest, queue)
queue.splice index, 1 if index > -1
# and then reject the deferred
dfd.rejectWith ajaxOpts.context or ajaxOpts, [promise, statusText, ""]
promise
promise
) jQuery
#!
# * jQuery LiveSearch
# *
# * Dual licensed under the MIT and GPL licenses:
# * http://www.opensource.org/licenses/mit-license.php
# * http://www.gnu.org/licenses/gpl.html
#
$.fn.livesearch = (callback, timer) ->
lastKeyPressCode = undefined
timeout = null
$input = $(this)
timer = 200 if typeof timer is "undefined"
$input.blur ->
$t = $(this)
v = $t.val()
unless v is $t.data("prev")
$t.data "prev", v
callback()
$input.each ->
$t = $(this)
$t.data "prev", $t.val()
$input.keydown (e) ->
$t = $(this)
lastKeyPressCode = e.keyCode
switch e.keyCode
# up
when 38, 40 # down
, 9 # tab
#case 13: // return
, 13
callback()
else
clearTimeout timeout if timeout
timeout = setTimeout(->
return if lastKeyPressCode is 46 or (lastKeyPressCode > 8 and lastKeyPressCode < 32)
v = $t.val()
return if v is $t.data("prev")
$t.data "prev", v
callback() if v.length >= 2 or v.length is 0
, timer)
$input
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment