这是场景:
我想将依赖项注入到由第三方库执行的回调函数中。这很简单,因为我可以将回调包装在一个闭包中 - 但问题源于我还希望能够在需要它的函数之外使用该依赖项的任何修改属性。
我举个例子。首先,示例用例:
动态构造app.[verb]
调用Express.js
- 该[verb]
属性由用户手动设置,如下所示:
项目控制器.js:
exports.create = function(req, res, $scope) {
$scope.method = 'post';
$scope.path = 'item/create';
res.send('Creates a new item');
};
假设我有一个injector
对象,其process
方法将函数所需的依赖项作为数组返回:
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;
}
我将如何确保每个方法都itemController.js
获得它自己的唯一实例$scope
,并且app[verb]
调用是动态构造成这样的?:
app.post('/item/create', function(req, res) {
res.send('Creates a new item');
});