属性が必要な特定のJavascriptメソッド、一致させるパターン、一致しない場合の対応方法を指定する方法があります。メソッドシグネチャを強制するためのJavascriptライブラリはありますか?
これは、メソッドレベルで必須およびオプションのパラメータをチェックするためのコードが繰り返し発生するためです。
この例を取ってください。ここで私はライトボックスを作りたいと思います。彼らが私に文字列を送ると、ちょうど内容のライトボックスを表示します。彼らが私にオプションオブジェクトを送ると、私は 'タイトル'と 'コンテンツ'を探します。標準化された方法でこれを指定できるのはすばらしいことではないでしょうか?
// Static method for generating a lightbox
// callerOptions = '' //if sent a string, the lightbox displays it with no title
// callerOptions = {
// content: '' // required popup contents. can be HTML or text.
// , title: '' // required title for the lightbox
// , subtitle: '' // optional subtitle for lightbox
// }
lightbox = function (callerOptions) {
if (!callerOptions) {
log.warn(_myName + ': calling me without a message to display or any options won\'t do anything');
return;
}
// If they send us a string, assume it's the popup contents
if (typeof(callerOptions) === 'string') {
this.options = {};
this.options.content = callerOptions;
// Otherwise assume they sent us a good options object
} else {
this.options = callerOptions;
}
_build();
_contentLoaded();
};
私はこのような何かを聞いたことがないいくつかのライブラリを使用できるようにするのが大好きです:
// Maybe this is what it looks like with a method signature enforcement library
lightbox = function (callerOptions) {
TheEnforcer(
, { valid: [
'string' // assumes that it is testing type against arguments by convention
, 'typeof([0].title) === "string" && typeof([0].content) === "string"'
]
}
});
// If they send us a string, assume it's the popup contents
if (typeof(callerOptions) === 'string') {
this.options = { 'content': callerOptions };
// Otherwise we know they sent us a good options object
} else {
this.options = callerOptions;
}
_build();
_contentLoaded();
};
は、誰もが今までこのようなJavaScriptライブラリを見ていますか?おそらく1000のJS MV *フレームワークの1つに組み込まれていますか?
編集: は通常、MV *フレームワークによって世話をである。このように思えます。 Backbone.jsにはモデルのプロパティの検証とデフォルト値の両方があります。私は、これらがここにあるユースケースを満たすために、またはほぼ満たすことができると思います。
私は、あなたが意図していない方法で動作するように強制するべきではないと思います。ちょうど私の意見。 – bfavaretto
ライトボックスに渡されるデータを処理する「ヘルパークラス」を作ってみませんか?ライトボックスは、パラメータをチェックするのではなく、行うべきことをする必要があります。 Btwのtypeofは角括弧なしで使用されます。 – Bakudan
ここで角括弧は "TheEnforcer"がテスト対象として引数の配列を使用すると推測しています。すみませんでした。ごめんなさい – SimplGy