Reputation: 2944
Here's the scenario:
I want to inject dependencies into a callback function that is executed by a third party library. This is simple enough, as I can wrap the callback in a closure - but the issue stems from the fact that I also want to be able to use any modified properties of that dependency outside of the function that requires it.
I'll give an example. First off, the example use case:
Dynamically constructing app.[verb]
calls in Express.js
- the [verb]
property is manually set by the user like so:
ItemController.js:
exports.create = function(req, res, $scope) {
$scope.method = 'post';
$scope.path = 'item/create';
res.send('Creates a new item');
};
Say I have an injector
object, with a process
method that returns the function's required dependencies as an array:
injector.process = function(fn) {
// RegExp constant matching code comments
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,
// convert the function to a string and strip any comments out
fnString = fn.toString().replace(STRIP_COMMENTS, ''),
// find the opening and closing parentheses of the function
openParenIndex = fnString.indexOf('('),
closeParenIndex = fnString.indexOf(')'),
// slice the content between the parens to their own string
contents = fnString.slice(openParenIndex + 1, closeParenIndex),
// convert contents to an array, split by comma or whitespace
args = contents.match(/([^\s,]+)/g);
// if the function expects no arguments, we need to specify an empty array
if (args === null) { args = []; }
// return an array of the expected arguments
return args;
}
How would I ensure that each method of itemController.js
gets it's own unique instance of $scope
, and that the app[verb]
call is dynamically constructed into something like this?:
app.post('/item/create', function(req, res) {
res.send('Creates a new item');
});
Upvotes: 1
Views: 169
Reputation: 1892
Try creating a the functions in an object like this,
var app = {
post : function() {
alert('posted');
},
get : function() {
alert('got');
}
}
Then you could call a function like this. (Lets say verb
has function name)
app[verb](); //if verb = "post" it will alert "posted"
I hope this is what you wanted.
Upvotes: 1