Skip to content

Instantly share code, notes, and snippets.

@paulja
Last active November 17, 2016 17:28
Show Gist options
  • Save paulja/7483106 to your computer and use it in GitHub Desktop.
Save paulja/7483106 to your computer and use it in GitHub Desktop.
Node.js Example of the `bind` method to chaining functions.
// -----------------------------------------------------------------
// Bind example
//
// Paul Jackson (pjackson@gmail.com)
// http://blog.paulj.me/
// -----------------------------------------------------------------
// Dependencies
var util = require('util')
, EventEmitter = require('events').EventEmitter;
// -----------------------------------------------------------------
// Worker Class
function Worker() {
EventEmitter.call(this);
}
util.inherits(Worker, EventEmitter);
Worker.prototype.doWork = function (workItem) {
this.emit('work', workItem);
}
// -----------------------------------------------------------------
// Handler Class
function Handler() {
EventEmitter.call(this);
}
util.inherits(Handler, EventEmitter);
Handler.prototype.process = function (workItem) {
this.emit('processing', workItem);
}
// -----------------------------------------------------------------
// Main
var worker = new Worker();
var handler = new Handler();
// Wire up handler
handler.on('processing', function (item) {
console.log('Processing: ', item);
});
// Chain the worker and the processor with BIND
worker.on('work', handler.process.bind(handler));
// Call the worker—Calling `doWork` here causes the
// `work` event to fire, which in turn, due to the
// `bind`, causes the `process` method to be called,
// which finally emits its `processing` event, handled
// above—proxy in action.
worker.doWork('Hello world');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment