Created
August 16, 2013 18:20
-
-
Save innerfunction/6252243 to your computer and use it in GitHub Desktop.
Node.js module for capturing parameter values being passed to a dust.js helper.
For example, if calling a helper {@Helper p1="{p1}" p2="{p2}"/}, this code will resolve values for p1 and p2 in a fully asynchronous manner before calling the helper function. Use the wrapper function as: var wrapper = require('./capture-helper-params'); helpers['myh…
This file contains hidden or 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
// Capture templated parameter values passed to a dust.js helper function. | |
function captureParams(chunk, context, params, cb) { | |
// Object for recording resolved parameter values. | |
var values = {}; | |
// Capture a single parameter value. | |
// @param {name} The parameter name. | |
// @param {next} Next step in the capture chain. | |
function capture( name, next ) { | |
return function( chunk ) { | |
// If the parameter value is a function then it is a dust.js template that needs to be | |
// resolved against the current context. | |
if( typeof params[name] == 'function' ) { | |
// Capture the parameter value. | |
return chunk.capture( params[name], context, function( value, chunk ) { | |
// Record the value and continue to the next item. | |
values[name] = value; | |
next( chunk ).end(); | |
}); | |
} | |
else return chunk.map(function( chunk ) { | |
// Parameter has a non-templated value, record it and continue to the next item. | |
values[name] = params[name]; | |
next( chunk ).end(); | |
}); | |
}; | |
} | |
// Final step in capture chain. Return the current chunk and the resolved parameter values. | |
var fn = function( chunk ) { | |
return cb( chunk, values ); | |
} | |
// Setup a chain of functions to capture each parameter value. | |
for( var id in params ) { | |
fn = capture( id, fn ); | |
} | |
// Execute the first function in the capture chain. | |
fn( chunk ).end(); | |
} | |
// A wrapper for helper functions. Captures all parameter values before invoking the helper function. | |
// Note: The helper function will be wrapped in a chunk.map() so chunk.end() must be called after all | |
// data has been written. | |
// @param {fn} The helper function. | |
module.exports = function( fn ) { | |
var self = this; | |
return function( chunk, context, bodies, params ) { | |
return chunk.map(function( chunk ) { | |
captureParams( chunk, context, params, function( chunk, params ) { | |
return fn.call( self, chunk, context, bodies, params ); | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment