[英]How to access unique injected dependency values outside of the function that required them in JavaScript
這是場景:
我想將依賴項注入到由第三方庫執行的回調函數中。 這很簡單,因為我可以將回調包裝在閉包中,但是問題出在我還希望能夠在需要依賴的函數之外使用依賴的任何修改屬性。
我舉一個例子。 首先,示例用例:
在Express.js
動態構造app.[verb]
調用-用戶手動設置[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');
});
嘗試在這樣的對象中創建函數,
var app = {
post : function() {
alert('posted');
},
get : function() {
alert('got');
}
}
然后,您可以調用這樣的函數。 (假設verb
具有函數名稱)
app[verb](); //if verb = "post" it will alert "posted"
希望這就是您想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.