今天随手写个发布订阅的 event.js

相信大家对发布订阅肯定很熟悉吧,很多场景都应用到了发布订阅;

例如自定义的一些事件,通过自定义的‘事件’,通过某个点触发;

例如:promise的原理其实和发布订阅也有一些的关系;将成功,失败,或者的必须做的函数分别放在数组中,当promise返回成功时,则把成功的函数事件全部都发布出去;

 

今天我给大家写个发布订阅的event.js  ;相信有去看各种插件源码都可以看到这个文件

  function Event(){
                this._events={};
            }
            Event.prototype.on = function (type, fn, context = this) {
                if (!this._events[type]) {
                    this._events[type] = []
                }

                this._events[type].push([fn, context])
            }

            Event.prototype.once = function (type, fn, context = this) {
                function magic() {
                    this.off(type, magic)

                    fn.apply(context, arguments)
                }
                // To expose the corresponding function method in order to execute the off method
                magic.fn = fn

                this.on(type, magic)
            }

            Event.prototype.off = function (type, fn) {
                let _events = this._events[type]
                if (!_events) {
                    return
                }

                let count = _events.length
                while (count--) {
                    if (_events[count][0] === fn || (_events[count][0] && _events[count][0].fn === fn)) {
                        _events[count][0] = undefined
                    }
                }
            }

            Event.prototype.trigger = function (type) {
                let events = this._events[type]
                if (!events) {
                    return
                }

                let len = events.length
                let eventsCopy = [...events]
                for (let i = 0; i < len; i++) {
                    let event = eventsCopy[i]
                    let [fn, context] = event
                    if (fn) {
                        fn.apply(context, [].slice.call(arguments, 1))
                    }
                }
            }

 

 

demo:

            var bs=new Event();
            bs.on('click',function(){console.log(111)},window);
            var aaa=333;
            bs.on('click',function(){console.log(this.aaa)},window);
            bs.once('click',function(){console.log('once')},window);
            console.log(bs._events)
            bs.trigger('click')

            console.log(bs._events)
            bs.trigger('click')
            console.log(bs._events)

 

结果截图:

 

转载于:https://www.cnblogs.com/heyinwangchuan/p/8562852.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值