jquery-longpoll-client
Version:
Simple client-side longpoll implementation
7 lines • 1.41 kB
JavaScript
/**
* jQuery LongPoll client script.
*
* @license https://opensource.org/licenses/BSD-3-Clause
* @author Viktor Khokhryakov <viktor.khokhryakov@gmail.com>
*/
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a("object"==typeof exports?require("jquery"):jQuery)}(function(a){"use strict";function b(b,c){function e(){i=a.ajax({type:f.type,url:f.url,data:g,dataType:"json"}).done(function(b){a.each(b.params,function(c,d){if(g[c]!==d)return g=b.params,a.isFunction(j.callback)&&j.callback.call(j,b.data),!1}),h=setTimeout(e,f.pollInterval)}).fail(function(a){a.status&&(h=setTimeout(e,f.pollErrorInterval))}).always(function(){i=null})}var f=a.extend({},d,c||{});if(!a.isPlainObject(f.params)||a.isEmptyObject(f.params))throw new Error('Invalid "params" property');var g=f.params,h=null,i=null,j=this;this.callback=f.callback,this.getId=function(){return b},this.isActive=function(){return null!==i||null!==h},this.start=function(){j.isActive()||e()},this.stop=function(){null!==i&&i.abort(),null!==h&&(clearTimeout(h),h=null)}}a.longpoll={get:function(a){return c[a]},register:function(a,d){if("string"!=typeof a)throw new Error('The "id" must be a string');return void 0!==c[a]&&c[a].stop(),c[a]=new b(a,d),c[a]},destroy:function(a){void 0!==c[a]&&(c[a].stop(),delete c[a])}};var c={},d={type:"GET",url:void 0,params:void 0,callback:void 0,pollInterval:500,pollErrorInterval:5e3}});