5 psnc.BetterSession = function (options) {
6 $.extend(this, this.defaults, options);
8 // account for network delays and rendering time
10 this.expireAfter -= 5;
12 this.postponeWarn = _.debounce(this.warn, this.warnAfter * 1000);
13 this.postponeExpire = _.debounce(this.expire, this.expireAfter * 1000);
15 $(this.warnSel).find('button').on('click', $.proxy(this.ping, this));
17 // update session whenever user loaded sth with ajax...
18 $(document).ajaxComplete($.proxy(this.update, this, true));
19 // ...or in another window
20 $(window).on('storage', $.proxy(this.update, this));
27 psnc.BetterSession.prototype = {
33 pingUrl: '/session/ping/',
34 warnSel: '#better-sessions-warn',
35 expireSel: '#better-sessions-expire',
36 timerSel: '#better-sessions-timer'
39 update: _.throttle(function (local) {
40 if (this.expired) return;
42 $(this.warnSel).hide();
43 clearInterval(this.timer);
45 // postpone expire message and warning
47 this.postponeExpire();
49 // update timestamp only if it is local event
51 localStorage.setItem(this.key, new Date());
56 $.post(this.pingUrl, {}, function(response) {
57 // session is implicitly extended after every ajax request
58 if (response.status === 'expired')
64 this.timer = setInterval($.proxy(this.updateTimer, this), 1000);
66 $(this.warnSel).show();
72 $(this.warnSel).hide();
73 $(this.expireSel).show();
74 clearInterval(this.timer);
77 updateTimer: function() {
78 var remaining = Date.parse(localStorage.getItem(this.key)) - new Date() + (this.expireAfter * 1000);
79 $(this.timerSel).text((humanizeDuration(remaining, {language: 'pl', round: true}) || 'chwilÄ™'))