Skip to content

Instantly share code, notes, and snippets.

@myndzi
Last active August 10, 2016 02:59
Show Gist options
  • Select an option

  • Save myndzi/d67b8f6c36bc5e2011a508928653a006 to your computer and use it in GitHub Desktop.

Select an option

Save myndzi/d67b8f6c36bc5e2011a508928653a006 to your computer and use it in GitHub Desktop.
var EventEmitter = require('events').EventEmitter,
inherits = require('util').inherits;
var ID = 0;
function Fetcher(url) {
EventEmitter.call(this);
this.id = ID++;
this.url = url;
}
inherits(Fetcher, EventEmitter);
Fetcher.prototype.start = function () {
// do your thing
// when you download a thing:
this.emit('fetched', {
id: this.id,
thing: thingYouDownloaded
});
// when you're done:
this.emit('complete', { id: this.id });
};
io.on('connection', function (socket) {
socket.fetchers = { };
socket.on('fetch', function (url) {
var fetcher = new Fetcher(url);
socket.fetchers[fetcher.id] = fetcher;
socket.emit('fetcher', {
id: fetcher.id,
url: url
});
// these relay the event from the fetcher to the websocket
fetcher.on('fetched', function (thing) {
socket.emit('fetched', thing);
});
fetcher.on('complete', function (thing) {
// remove this fetcher from the active list
delete socket.fetchers[fetcher.id];
socket.emit('complete', fetcher.id);
});
});
// note: i don't remember this event and the docs aren't making it clear to me
socket.on('closed', function () {
Object.keys(socket.fetchers).forEach(function (key) {
var fetcher = socket.fetchers[key];
// stop doing things
fetcher.removeAllListeners();
// or:
fetcher.stop();
});
socket.fetchers = { };
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment