1 Star 0 Fork 0

Shadow / code-snippet

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
emitter.html 1.42 KB
一键复制 编辑 原始数据 按行查看 历史
Shadow 提交于 2022-04-20 19:54 . emitter名称修正
<script>
/*
* @Author: LiYu
* @Date: 2022-04-05 14:38:31
* @LastEditors: LiYu
* @LastEditTime: 2022-04-05 16:00:13
* @Description: 发布订阅
*/
class Emitter {
listenerSet = {};
on(name, callback) {
const listeners = this.listenerSet[name] || [];
listeners.push(callback);
this.listenerSet[name] = listeners;
}
emit(name, ...args) {
const listeners = this.listenerSet[name];
if (listeners) {
listeners.forEach(listener => {
listener.apply(this, args);
})
} else {
console.warn(`无监听者: ${name}`);
}
}
off(name, fn) {
const listener = this.listenerSet[name];
if (listener) {
const idx = listener.findIndex(callback => callback === fn);
if (idx >= 0) {
listener.splice(idx, 1);
}
} else {
console.warn(`无监听者: ${name}`);
}
}
once(name, callback) {
const fn = (...args) => {
callback.apply(this, args);
this.off(name, fn);
}
this.on(name, fn);
}
}
// test
const emitter = new Emitter();
emitter.on('post', (value) => {
console.log('on', value);
})
emitter.on('post', callback)
function callback(...args) {
console.log('on', args);
}
emitter.off('post', callback);
emitter.once('post', (...args) => {
console.log('once', args);
})
emitter.emit('post', 1, 2, 3);
</script>
1
https://gitee.com/ytiona/code-snippet.git
git@gitee.com:ytiona/code-snippet.git
ytiona
code-snippet
code-snippet
master

搜索帮助