1 Star 0 Fork 0

sc2nacl/test

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
eventBus.html 3.10 KB
一键复制 编辑 原始数据 按行查看 历史
sc2nacl 提交于 2021-08-19 12:54 . update
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>EventBus</title>
</head>
<body>
<div>
<button id="J_btn">btn1</button>
</div>
<script>
const eventBus = {
listeners: {},
addListener: function (type, callback, scope) {
if (typeof this.listeners[type] !== 'undefined') {
this.listeners[type].push({ scope: scope, callback: callback })
} else {
this.listeners[type] = [
{ scope: scope, callback: callback }
]
}
},
removeListener: function (type, callback, scope) {
if (typeof this.listeners[type] !== 'undefined') {
const numOfCallbacks = this.listeners[type].length
let newArray = []
for (let i = 0; i < numOfCallbacks; i++) {
let listener = this.listeners[type][i]
if (listener.scope === scope && listener.callback === callback) {
} else {
newArray.push(listener)
}
}
this.listeners[type] = newArray
}
},
removeAllListener: function () {
this.listeners = {}
},
hasListener: function (type, callback, scope) {
if (typeof this.listeners[type] !== 'undefined') {
const numOfCallbacks = this.listeners[type].length
if (callback === undefined && scope === undefined) {
return numOfCallbacks > 0
}
for (let i = 0; i < numOfCallbacks; i++) {
const listener = this.listeners[type][i]
if (listener.scope === scope && listener.callback === callback) {
return true
}
}
}
return false
},
dispatch: function (type, event, shape) {
if (typeof this.listeners[type] !== 'undefined') {
const numOfCallbacks = this.listeners[type].length
for (let i = 0; i < numOfCallbacks; i++) {
let listener = this.listeners[type][i]
if (listener && listener.callback) {
listener.callback.apply(listener.scope, [event, shape])
}
}
}
},
}
</script>
<script>
eventBus.addListener('showModal', function(){
alert(121212)
})
document.querySelector('#J_btn').addEventListener('click', function(){
eventBus.dispatch('showModal')
})
</script>
</body>
</html>
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/sc2nacl/test.git
[email protected]:sc2nacl/test.git
sc2nacl
test
test
master

搜索帮助