美文网首页
事件总线EventBus

事件总线EventBus

作者: 欢西西西 | 来源:发表于2021-12-13 16:53 被阅读0次
// 使用一个对象来管理所有的事件和处理程序
// 优点:有效地降低消息发布者和订阅者之间的耦合度
function EventBus() {
    this._eventBus = {};
}
EventBus.prototype = {
    constructor: EventBus,
    isStrValid(str) {
        return str && Object.prototype.toString.call(str) === '[object String]';
    },
    // 监听
    $on(eventName, fn) {
        if (!this.isStrValid(eventName)) {
            console.error('请传入正确的事件名称');
            return;
        }
        let eventBus = this._eventBus,
            handlers = eventBus[eventName];
        if (!handlers) {
            eventBus[eventName] = [fn];
            return;
        }
        if (handlers.includes(fn)) {
            return;
        }
        handlers.push(fn);
    },
    // fn只执行一次
    $once(eventName, fn) {
        let that = this;
        let onceFn = function () {
            fn(...arguments);
            that.$off(eventName, onceFn);
        };
        this.$on(eventName, onceFn);
    },
    // 触发
    $fire(eventName, ...args) {
        if (!this.isStrValid(eventName)) {
            console.error('请传入正确的事件名称');
            return;
        }
        let arrHandler = this._eventBus[eventName];
        if (!arrHandler || !arrHandler.length) {
            return;
        }
        arrHandler.forEach(fn => {
            fn(...args);
        });
    },
    // 解绑
    $off(eventName, ...fns) {
        if (!arguments.length) {
            // 解绑所有事件
            this._eventBus = {};
            return;
        }
        if (!this.isStrValid(eventName)) {
            console.error('请传入正确的事件名称');
            return;
        }
        if (!fns.length) {
            // 解绑所有的eventName事件
            delete this._eventBus[eventName];
            return;
        }
        // 解绑fns
        let handlers = this._eventBus[eventName];
        this._eventBus[eventName] = handlers.filter(fn => !fns.includes(fn));
    },
};

相关文章

  • [Android组件解读] EventBus3.0解析

    记得前段时间讲解过otto事件总线的概念,但是大家习惯用的事件总线应该还是EventBus。 EventBus介绍...

  • eventBus源码解析

    EventBus定义:是一个发布 / 订阅的事件总线。 发布者,订阅者,事件,总线。 EventBus,可以说,就...

  • Vue的事件总线

    事件总线是什么? EventBus 又称为事件总线。在Vue中可以使用 EventBus 来作为沟通桥梁的概念,就...

  • EventBus和RxBus的使用

    EventBus介绍: Rx:函数响应式编程,EventBus:事件总线 。EventBus 功能类似handle...

  • vue 事件总线EventBus的概念、使用

    两个组件之间毫无关系,用到 vue 中的事件总线 EventBus的概念来传递数据 EventBus又称事件总线,...

  • 事件总线知多少(1)

    源码路径:Github-EventBus事件总线知多少(1)事件总线知多少(2) 1. 引言 事件总线这个概念对你...

  • Android小技巧之来不及解释了快上车--EventBus3

    什么是EventBus 先附上EventBus的git地址 EventBus,就按照名字翻译来说"事件总线",官方...

  • EventBus原理解析

    EventBus(发布订阅事件总线):通过解耦发布者和订阅者简化android 事件传递 EventBus is ...

  • 事件总线知多少(2)

    源码路径:Github-EventBus事件总线知多少(1)事件总线知多少(2) 1.引言 之前的一篇文章事件总线...

  • EventBus源码分析

    EventBus EventBus是一个为Android和Java平台设计的发布/订阅事件总线 EventBus有...

网友评论

      本文标题:事件总线EventBus

      本文链接:https://www.haomeiwen.com/subject/fmzjfrtx.html