Last active
November 17, 2016 17:28
-
-
Save paulja/7483106 to your computer and use it in GitHub Desktop.
Node.js Example of the `bind` method to chaining functions.
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
// ----------------------------------------------------------------- | |
// 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