Last active
August 29, 2015 14:22
-
-
Save rhocairn/77dbd0b6413ad56526b6 to your computer and use it in GitHub Desktop.
Basic EventEmitter example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var SimpleQueue = require('./simple_queue'); | |
// Set up our SimpleQueue instance | |
var queue = SimpleQueue(); | |
queue.on(SimpleQueue.events.JobAdded, function(job) { | |
console.log("A job was added:", job); | |
}); | |
queue.on(SimpleQueue.events.NoJobs, function() { | |
console.log("Someone wanted to get a job, but none were in the queue"); | |
}); | |
queue.on(SimpleQueue.events.Drain, function() { | |
console.log("Someone just grabbed the last job!"); | |
}); | |
queue.on(SimpleQueue.events.JobFound, function(job) { | |
console.log("Someone just grabbed a job:", job); | |
}); | |
// Later on in this code, after we've gotten work to do (perhaps inside an Express app...) | |
queue.add('foo'); // Triggers JobAdded | |
queue.add('bar'); // Triggers JobAdded | |
queue.get(); // Triggers JobFound | |
queue.get(); // Triggers JobFound and Drain | |
queue.get(); // Triggers NoJobs |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var util = require('util'); | |
var EventEmitter = require('events').EventEmitter; | |
function SimpleQueue() | |
{ | |
return Object.create(SimpleQueue.prototype, { | |
jobs: { | |
value: [], | |
writable: true, | |
enumerable: true | |
} | |
}); | |
} | |
util.inherits(SimpleQueue, EventEmitter); | |
SimpleQueue.events = { | |
JobAdded: 'job_added', | |
NoJobs: 'no_jobs', | |
JobFound: 'job_found', | |
Drain: 'drain' | |
}; | |
SimpleQueue.prototype.add = function add(job) | |
{ | |
this.emit(SimpleQueue.events.JobAdded, job); | |
this.jobs.push(job); | |
} | |
SimpleQueue.prototype.get = function get() | |
{ | |
if (this.jobs.length == 0) { | |
this.emit(SimpleQueue.events.NoJobs); | |
return null; | |
} | |
var job = this.jobs.shift(); | |
this.emit(SimpleQueue.events.JobFound, job); | |
if (this.jobs.length == 0) { | |
this.emit(SimpleQueue.events.Drain); | |
} | |
return job; | |
} | |
module.exports = SimpleQueue; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment