1

シナリオは次のとおりです。

サードパーティ ライブラリによって実行されるコールバック関数に依存関係を挿入したいと考えています。コールバックをクロージャーでラップできるので、これは非常に簡単ですが、問題は、その依存関係の変更されたプロパティを、それを必要とする関数の外部でも使用できるようにしたいという事実から生じます。

例を挙げます。まず、ユースケースの例:

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');
});
4

1 に答える 1

1

このようなオブジェクトで関数を作成してみてください。

var app = {
    post : function() {
        alert('posted');
    },
    get : function() {
        alert('got');       
    }
}

次に、このような関数を呼び出すことができます。(verb関数名があるとしましょう)

app[verb](); //if verb = "post" it will alert "posted"

これがあなたの望むものであることを願っています。

于 2013-11-06T16:04:58.500 に答える