シナリオは次のとおりです。
サードパーティ ライブラリによって実行されるコールバック関数に依存関係を挿入したいと考えています。コールバックをクロージャーでラップできるので、これは非常に簡単ですが、問題は、その依存関係の変更されたプロパティを、それを必要とする関数の外部でも使用できるようにしたいという事実から生じます。
例を挙げます。まず、ユースケースの例:
app.[verb]
呼び出しを動的に構築するExpress.js
-[verb]
プロパティは次のようにユーザーによって手動で設定されます。
ItemController.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');
});