Skip to content

Instantly share code, notes, and snippets.

@timmfin
Last active December 2, 2015 23:49
Show Gist options
  • Save timmfin/5ce632f375c1c087a210 to your computer and use it in GitHub Desktop.
Save timmfin/5ce632f375c1c087a210 to your computer and use it in GitHub Desktop.
Thought experiement on broccoli v1 changes to more easily hook into and/or compose inputNodes
function MyPlugin(inputNodes, options) {
this.options = options;
// In this example, let's say we need to do something special with the first
// inputNode as compared to the others.
[this.firstNode, ...this.otherNodes] = inputNodes;
// Make sure we re-create event handlers new for every build (at least the ones
// that require state be reset between builds)
this.on('newBuild', () => {
this.firstNode.on('beginNode', this.options.startCallback); // pre-firstNode
this.firstNode.on('endNode', this.options.secondCallback); // post-firstNode
this.otherNodes.forEach(n => n.on('endNode', this.options.postEachOtherCallback));
// Make `finalCallback` only get called after _all_ input nodes are fully finished
// using the little eventComposeHelper util (included below). A bit superficial
// but illustates needing to "hook" into the completion of X different nodes
let callbackComposeHandlers = eventComposeHelper(inputNodes.length, this.options.finalCallback);
inputNodes.forEach((n, i) => n.on('endNode', callbackComposeHandlers[i]));
});
Plugin.call(inputNodes, options);
}
MyPlugin.prototype.build = function() {
// A more sane way to "hook" around the completion of _all_ passed inputNodes
// instead of the superfical above use of eventComposeHelper
// this.options.finalCallback();
// Whatever else this plugin wants to do in its build ...
}
// Event composition util, example usage:
//
// var a = eventComposeHelper(2, () => console.log('DONE'))
// a[0]()
// a[1]() // DONE logged
//
function eventComposeHelper(numCallbacksNeeded, whenDone) {
const callbacksCalled = Array(numCallbacksNeeded).fill(false);
function buildCallbackHandler(index) {
return function() {
callbacksCalled[index] = true;
if (callbacksCalled.every(x => x === true)) {
whenDone();
callbacksCalled.fill(false); // if we need to run `whenDone` multiple times
}
}
}
return Array(numCallbacksNeeded).fill(null).map((x, i) => buildCallbackHandler(i));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment