【发布时间】:2012-04-18 15:35:03
【问题描述】:
我想有一种方法来为某些 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 的模型属性同时具有验证值和默认值。我认为这些可以用来满足或几乎满足我在这里介绍的用例。
【问题讨论】:
-
我认为你不应该试图强迫一种语言以它不被设计的方式运行。只是我的意见。
-
为什么不创建一个“帮助类”来处理传递给灯箱的数据?灯箱应该做它打算做的事情,而不是检查参数。顺便说一句,typeof 不带括号使用。
-
这里的括号推断“TheEnforcer”使用一组参数作为测试对象。抱歉,不清楚
-
@bfavaretto +1 每种语言都有自己的哲学,你应该使用它,而不是试图忽略/避免/改变。了解该功能为何如此运作并为您所用。
-
@bfavaretto:我不同意这些“遵循语言的意图”的 cmets。这种态度似乎会阻止 jQuery。我说的是在这里添加一个特性,而不是让它表现得像一种经典语言。我认为这将是一个不可否认的有用功能。至于选择不同的语言,JS 本质上是基于 Web 的丰富交互的唯一选择。我们能做的最好的事情(事实上,就像其他人一直在做的那样)是构建框架来添加功能,并希望 ECMAscript 委员会能够挑选出好的功能。
标签: javascript architecture backbone.js unobtrusive-javascript signature