npm.io
1.0.1 • Published 11 years ago

workhorsejs

Licence
MIT
Version
1.0.1
Deps
2
Vulns
0
Weekly
0

workhorse.js

web workers on crack! (should have called it whitney)

The goal behind workhorse is to simplify messaging between a worker and client interface. It also adopts some concepts from the ServiceWorker spec.

Events

on(event, handler)

var worker = new Workhorse('thing.js');

worker.on('wat', function (e) {
  console.log(e.data);
});
off(event, [handler])
// remove all the "wats"
worker.off('wat');
emit(event, [data])
worker.on('wat', function (e) {
  console.log(e.data.message);
});
worker.emit('wat', { message : 'hi!' }); // => "hi!"
once(event, handler)
worker.once('wat', function () {
  console.log('hi!');
});
worker.emit('wat'); // => "hi!"
worker.emit('wat'); // nothin'
post(event, data)
worker.post('wat', { message: 'hi' });
What are the differences between emit and post?
  • post sends a message across the wire, this would be the equivilant of postMessage.
  • emit triggers any and all event handlers associated with an event. This does not send a message across the wire.
Responding to events

By default web workers offer a very simple messaging system which can get messy quick when a worker potentially has multiple responsibilities.

Rather than wiring up multiple events for a game of ping pong, we should be able to easily respond to an event via the event object.

worker.on('wat', function (event) {
  event.respondWith({
    message: 'Hello!'
  });
});
Recieving responses

So just like the issue of responding to events, how does a client recieve that response without wiring up an additional event? This seems like a fitting place to use promises.

worker.post('wat', { wat: 'wat' })
  .then(function (response) {
    console.log(response.message); // => "Hello!"
  });
Considerations

Things to consider while developing

  • There are multiple types of workers (Worker, SharedWorker, etc.)
  • It's possible to spin up a worker via port property (worker.port)
  • Nothing could probably ever take Whitney in a fist fight

Keywords