<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button id="button1">clear</button>
<button id="button2">000</button>
<script type="text/javascript">
var Event = {
_listeners: {},
addEvent: function(type, fn) {
if (typeof this._listeners[type] === "undefined") {
this._listeners[type] = [];
}
if (typeof fn === "function") {
this._listeners[type].push(fn);
}
return this;
},
fireEvent: function(type) {
var arrayEvent = this._listeners[type];
if (arrayEvent instanceof Array) {
for (var i=0, length=arrayEvent.length; i<length; i+=1) {
if (typeof arrayEvent[i] === "function") {
arrayEvent[i]();
}
}
}
return this;
},
removeEvent: function(type, fn) {
var arrayEvent = this._listeners[type];
if (typeof type === "string" && arrayEvent instanceof Array) {
if (typeof fn === "function") {
for (var i=0, length=arrayEvent.length; i<length; i+=1){
if (arrayEvent[i] === fn){
this._listeners[type].splice(i, 1);
break;
}
}
} else {
delete this._listeners[type];
}
}
return this;
}
};
//------------- 以下为测试代码 -----------
// 添加自定义事件
var fnAlert1, fnAlert2;
Event.addEvent("alert", fnAlert1 = function() {
alert("第一个弹出!");
}).addEvent("alert", fnAlert2 = function() {
alert("第二个弹出!");
});
// 按钮绑定事件,用来清除自定义事件
var elButton1 = document.getElementById("button1"),
elButton2 = document.getElementById("button2");
elButton1.onclick = function() {
//Event.removeEvent("alert");
alert("alert事件清除成功!");
// 此时后一个按钮卧底了,故隐藏
elButton2.style.display = "none";
};
elButton2.onclick = function() {
Event.removeEvent("alert", fnAlert1);
alert("第一个alert清除成功!");
};
// 点击文档,触发自定义事件
document.onclick = function(e) {
e = e || window.event;
var target = e.target || e.srcElement;
// 如果文档点击元素标签名不是input
if (!target || !/input|pre/i.test(target.tagName)) {
Event.fireEvent("alert");
}
};
</script>
</body>
</html>
链接:https://www.zhangxinxu.com/study/201203/js-custom-events-literal.html