今天随手写个发布订阅的 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)
结果截图: