-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathjquery.work.min.js
More file actions
16 lines (15 loc) · 2.45 KB
/
jquery.work.min.js
File metadata and controls
16 lines (15 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
* jQuery Parallel v0.2 plugin for jQuery.
*
* Allows easy use of Web Workers by wrapping them in a Deferred object.
*
* Copyright (c) 2011 Jonathan Cardy
* Licensed under the MIT licenses.
*/
var currentFilename="jquery.work.min.js";if(typeof window==="undefined"){self.addEventListener('message',function(event){var action=self._getFunc(event.data.action);var result=action(event.data.args,self);self._postResult(result);},false);self.notify=function(obj){obj=obj||{};self.postMessage({notify:obj});};self.complete=function(obj){obj=obj||{};self.postMessage({complete:obj});};self.timeout=function(func,t){func();};self._postResult=function(result){result=result||{};self.postMessage({result:result});};self._getFunc=function(funcStr){var argNames=funcStr.substring(funcStr.indexOf("(")+1,funcStr.indexOf(")")).split(",");funcStr=funcStr.substring(funcStr.indexOf("{")+1,funcStr.lastIndexOf("}"));return new Function(argNames,funcStr);};}
if(typeof jQuery!=="undefined"){(function($){if(!$.Deferred){throw"This plugin uses Deferred objects and jQuery >= 1.5 must be loaded.";}
$.work=function(action,args,options){var promise,def=$.Deferred(),callbacks=[],notifications=[],wrappedDef={notify:function(obj){var i;for(i=0;i<callbacks.length;i++){callbacks[i].call(this,obj);}
notifications.push(obj);}};$.extend(def,wrappedDef);def.complete=function(obj){def.resolve(obj);};options=options||{};$.extend({debug:false,awaitComplete:false},options);if(window.Worker&&!options.debug){if(window.location.protocol==="file:"){throw"Web Workers only support access via HTTP.";}
var worker=new Worker(currentFilename);worker.addEventListener('message',function(event){if(event.data.notify){def.notify(event.data.notify);}else if(event.data.result){if(!options.awaitComplete){def.resolve(event.data.result);}}else if(event.data.complete){def.complete(event.data.complete);}},false);worker.addEventListener('error',function(event){def.reject(event);},false);worker.postMessage({action:action.toString(),args:args});}else{setTimeout(function(){try{var result=action(args,{notify:function(obj){def.notify(obj);},complete:function(obj){def.complete(obj);},timeout:function(func,t){setTimeout(function(){func();},t);}});if(!options.awaitComplete){def.resolve(result);}}catch(e){def.reject(e);}},0);}
promise=def.promise();promise.progress=function(callback){var n;callbacks.push(callback);for(n=0;n<notifications.length;n++){callback.call(promise,notifications[n]);}
return promise;};return promise;};}(jQuery));}