编写一个自定义事件类,包含on/off/emit/once方法

匿名 (未验证) 提交于 2019-12-02 23:57:01
function Event() {   this._events = {}; }  Event.prototype.on = function(type, fn) {   if (!this._events[type]) {     this._events[type] = []   }   this._events[type].push(fn); }  Event.prototype.off = function(type, fn) {   if (!this._events[type]) {     return;   }   if (!fn) {     this._events[type] = undefined;     return;   }   var index = this._events[type].indexOf(fn);   this._events[type].splice(index, 1); }  Event.prototype.emit = function(type) {   if (!this._events[type]) {     return;   }   this._events[type].forEach(fn => fn()); }  Event.prototype.once = function(type, fn) {   var _ = this;   var _fn = () => {     fn.apply(_, arguments);     this.off(type);   };    this.on(type, _fn); }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!