特定の 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 には、モデルのプロパティに検証値とデフォルト値の両方があります。これらは、ここで紹介するユースケースを満たす、またはほぼ満たすために使用できると思います。