粗略地说:
var Confirm = (function()
function Confirm(element, message) {
var self = this;
this.message = message;
hookEvent(element, "click", function(event) {
self.doConfirm(event);
});
}
Confirm.prototype.doConfirm = Confirm$doConfirm;
function Confirm$doConfirm(e) {
if (!confirm(this.message)) {
if (e.stopPropagation) {
e.stopPropagation();
}
else {
e.cancelBubble = true;
}
if (e.preventDefault) {
e.preventDefault();
}
else {
e.returnValue = false;
}
}
}
return Confirm;
})();
(您可以缩短略有如果你不介意使用匿名函数;我更喜欢help my tools help me通过给函数的名称)
在上面,hookEvent
是一个实用函数,您必须提供,要么调用addEventListener
或attachEvent
(以支持IE8和更早版本),如下所示:
function hookEvent(element, eventName, handler) {
// Very quick-and-dirty, recommend using a proper library,
// this is just for the purposes of the example.
if (typeof element.addEventListener !== "undefined") {
element.addEventListener(eventName, handler, false);
}
else if (typeof element.attachEvent !== "undefined") {
element.attachEvent("on" + eventName, function(event) {
return handler(event || window.event);
});
}
else {
throw "Browser not supported.";
}
}
注意跨浏览器兼容性需要多少工作量。您不必使用Prototype,但我强烈建议您使用另一个像样的库,即使不是Prototype,如jQuery,YUI,Closure或any of several others。您将节省lot努力解决跨浏览器差异,并处理利用其他人在这一领域所做的重要工作而提出的边缘案例。
如果你的目标是将关闭的原型,而不是完全动过库,这里是使用jQuery例如同样的事情:使用$().click
为hookEvent
,$.proxy
以避免产生一个明确的关闭(仍然
var Confirm = (function()
function Confirm(element, message) {
this.message = message;
$(element).click($.proxy(this.doConfirm, this));
}
Confirm.prototype.doConfirm = Confirm$doConfirm;
function Confirm$doConfirm(e) {
if (!confirm(this.message)) {
return false;
}
}
return Confirm;
})();
创建一个,只是在幕后为你做),事实上,在jQuery事件处理程序中,return false
与停止传播和阻止默认操作(就像Prototype的stop
)一样。您也可以使用stopPropagation
和preventDefault
,而不用担心浏览器的差异; jQuery为你处理它。大多数图书馆都会
如果你离开Prototype,但仍然想要类似Class
功能,here's one,你可以放入你的代码。我在该博客文章中的目标不是取代Prototype的Class
(当时我正在使用Prototype),而是解决了我发现Prototype的巨大处理超级调用的低效方式。但是在这样做的时候,一个完整的实现可以替代Class
创建。我真的需要更新其中的术语,因为它当然不是关于类(JavaScript没有类),它只是用于JavaScript的原型继承的一些方便的管道工具。
原型是JavaScript的。 – Jeff 2012-01-05 15:16:37
@FelixKling。这个在我最喜欢的酒吧中排名第一。 – 2012-01-05 15:19:03