Skip to content

deebloo/worker

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

worker

A tiny micro library to help make using web workers easier.

For more info on web workers look here

Install

bower install --save worker

Basic Usage

var myWorker = $worker().create(function(e) {
  var sum = 0;
  
  e.data.forEach(function(int) {
    sum += int;
  });
  
  self.postMessage(sum);
});

myWorker.onmessage = function(data) {
  console.log(data);
};

myWorker.postMessage([1,2,3,4,5]);

API

$worker().create

creates a new web worker

Arg Type description
func Function the code to be used in the web worker

Example:

var myWorker = $worker().create(function(e) {
  var sum = 0;
  
  e.data.forEach(function(int) {
    sum += int;
  });
  
  self.postMessage(sum);
});

myWorker.postMessage

Post data for the web worker to use. Runs the web worker

Arg Type description
data * the data to be posted (cannot be function)

Example:

myWorker.postMessage([1,2,3,4,5]);

myWorker.onmessage

Override this method. This method is called whenever your $worker posts data back.

Arg Type description
data * the data that is posted back from the worker

Example:

myWorker.onmessage = function(data) {
  console.log(data);
};

myWorker.loadScripts

Sometimes you need to load functions into your worker. $worker.loadScripts loads a list of functions into the web worker that can be used by the worker.

NOTE: anything other then functions should be passed in with postMessage

Arg Type description
* Object A map of functions and the name they should be stored under
myWorker.loadScripts({
  'hello': function() {
    return 'hello';
  }, 
  'goodbye': function() {
    return 'goodbye';
  }
});

myWorker.removeScripts

Remove injected scripts from the web worker

Arg Type description
* String A list of function names to be removed.
myWorker.removeScripts('hello', 'goodbye');

Complete Example

var group = $worker();

var myWorker = group.create(function(e) {
  var foo = [], min = e.data.min, max = e.data.max;
  
  for (var i = 0; i < e.data.length; i++) {
    foo.push(Math.floor(Math.random() * (max - min)) + min);
  }
  
  // function passed in from the loadScripts api
  hello();

  self.postMessage(foo);
});

myWorker.loadScripts({
  'hello': function hello() { console.log('yay')}
});

myWorker.onmessage = function(data) {
  result = data;
};

myWorker.postMessage({length: 1024, min: 0, max: 9999});

About

A tiny library to make using web workers easier.

Resources

License

Stars

Watchers

Forks

Packages

No packages published