<!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>javascript
<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;
}
};html
//------------- 如下爲測試代碼 -----------java
// 添加自定義事件
var fnAlert1, fnAlert2;
Event.addEvent("alert", fnAlert1 = function() {
alert("第一個彈出!");
}).addEvent("alert", fnAlert2 = function() {
alert("第二個彈出!");
});測試
// 按鈕綁定事件,用來清除自定義事件
var elButton1 = document.getElementById("button1"),
elButton2 = document.getElementById("button2");this
elButton1.onclick = function() {
//Event.removeEvent("alert");
alert("alert事件清除成功!");
// 此時後一個按鈕臥底了,故隱藏
elButton2.style.display = "none";
};htm
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>ip
</body>
</html>rem
連接:https://www.zhangxinxu.com/study/201203/js-custom-events-literal.html文檔