我想有一种方法来为某些 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* 框架之一?
编辑:似乎这通常由 MV* 框架处理。Backbone.js 的模型属性同时具有验证值和默认值。我认为这些可以用来满足或几乎满足我在这里介绍的用例。