Skip to content

Instantly share code, notes, and snippets.

@maxp
Created September 24, 2014 13:30
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 maxp/84420ae7898a193cdc93 to your computer and use it in GitHub Desktop.
Save maxp/84420ae7898a193cdc93 to your computer and use it in GitHub Desktop.
#
# mlib: common client js routines v0.5.0
# m@penzin.ru
#
# -- globals --
window.lib = x = {}
# window._csrf used as token, replaced by _csrf cookie if empty
# -- ES5 emulation --
unless String::trim then String::trim = -> this.replace(/^\s+|\s+$/g, "")
unless Array::forEach then Array::forEach = (action, that) ->
i = 0; n = this.length
while i < n
action.call(that, this[i], i, this) if i in this
i++
return null
#-
# -- util --
x.int = (s, def) ->
i = parseInt(s, 10)
return if not isNaN(i) then i else def
#-
x.str = str = (s) ->
return if (not s?) or (typeof s is "number" and isNaN(s)) then "" else ""+s
#-
x.randInt = (n) -> Math.floor(Math.random()*n)
x.htmlq = (s) ->
s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;')
#-
# -- errmsg --
ERRMSG_TEXT = {
parsererror:"Ошибка в ответе сервера."
timeout: "Таймаут запроса."
error: "Ошибка при соединении с сервером."
abort: "Запрос прерван."
#
nimp: "Функциональность не реализована."
db: "Ошибка базы данных."
sys: "Ошибка на сервере."
req: "Ошибка в запросе."
}
x.errmsg = (err) ->
return err.msg if err?.msg
return ERRMSG_TEXT[err?.err] or "Неизвестная ошибка!" # TODO: _trace
#-
# default error handler
post_errmsg = (err) -> alert(x.errmsg(err))
# -- http --
x.get_cookie = get_cookie = (name) ->
cookies = window.document.cookie?.split(';')
return if not cookies
name += "="; nl = name.length
for c in cookies
c = c.trim()
return decodeURIComponent(c.substring(nl)) if c.substring(0, nl) is name
#-
# NOTE: modification of global window._csrf
x.csrf_token = () -> window._csrf ?= (get_cookie("_csrf") or false)
x.AJAX_TIMEOUT = 100*1000
x.post = (url, data, success, error=post_errmsg) ->
$.ajax {
url: url, data: JSON.stringify(data), timeout: x.AJAX_TIMEOUT,
type: 'POST', dataType: 'json', contentType: 'application/json',
beforeSend: (xhr) ->
xhr.setRequestHeader('x-csrf-token', csrf) if (csrf = x.csrf_token())
success: (data) -> if data?.ok then success(data) else error(data)
error: (xhr, status, text) -> error({err:status, text:text})
}
#-
x.get = (url, data, success, error=post_errmsg) ->
$.ajax {
url: url, data: data, type: 'GET', dataType: 'json', timeout: x.AJAX_TIMEOUT,
success: (data) -> if data?.ok then success(data) else error(data)
error: (xhr, status, text) -> error({err:status, text:text})
}
#-
x.trace = (qs, data) ->
$.ajax {
url: '/_trace' + (qs and ("?"+qs) or "")
type: 'POST'
timeout: 30*1000
dataType: 'json'
contentType: 'application/json'
data: JSON.stringify(data)
done: () -> # ignore result
}
#-
# -- date --
_d02 = (d) -> if d < 10 then "0"+d else ""+d
x.hhmm = (date) ->
return "??:??" if not date
return _d02(date.getHours())+":"+_d02(date.getMinutes())
#-
x.hhmmss = (date) ->
return "??:??:??" if not date
return _d02(date.getHours())+":"+_d02(date.getMinutes())+":"+_d02(date.getSeconds())
#-
x.ddmmyyyy = (date) ->
return "??.??.????" if not date
return _d02(date.getDate())+"."+_d02(date.getMonth()+1)+"."+date.getFullYear()
#-
# -- validators --
# returns valid value or ""
# NOTE: only +7 phone matched
x.cleanup_phone = (phone) ->
phone = str(phone).replace(/[^0-9\+]/gi, '')
phone = phone.substr(1) if phone[0] == '8'
phone = "7"+phone if phone.length == 10
phone = "+"+phone if phone[0] != '+'
return if phone.match(/^\+7\d{10}$/) then phone else ""
#-
# NOTE: maxlength is 80, does not allow '+' in username
x.cleanup_email = (eml) ->
eml = str(eml).trim()
return "" if eml.length > 80
return "" if not eml.match(/^[0-9a-z\.\-\_]+@([0-9a-z\-]+\.)+([a-z]){2,}$/i)
return eml
#-
# -- events --
x.delayed_handler = (func, args, timeout=200) ->
th = null
() ->
return if th
th = setTimeout(
() ->
func(args)
th = null
,
timeout
)
#-
#-
# field modification events for jQuery.on()
x.ON_CHANGE_EVENTS = "blur change keyup keypress cut paste"
# example: $("#fild").on(ON_CHANGE_EVENTS, delayed_handler( validator_routine ))
#.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment