class Event{ constructor(){ this.handlers=[] } on(type,fn){ //订阅事件 if(!this.handlers[type]){ this.handlers[type] = []; } this.handlers[type].push({handle:fn,one:false}); } one(type,option={},fn){ //订阅只执行一次的事件 if(!this.handlers[type]){ this.handlers[type] = []; } this.handlers[type].push({handle:fn,one:true}); } emit(type,option,fn){ //发布某类事件或者某个事件,fn存在时候只执行订阅过的fn事件 var handlers = this.handlers[type] for (var i=0, len=handlers.length; i < len; i++){ if(fn){ if(handlers[i].handle === fn){ handlers[i].handle(option) if(handlers[i].one){ handlers.splice(i, 1); } break; } }else { handlers[i].handle(option) if(handlers[i].one){ handlers.splice(i, 1); } } } } remove(type,fn){ //移除某类事件或者某个事件,fn存在即移除该事件 var handlers = this.handlers[type] if(fn){ for (var i=0, len=handlers.length; i < len; i++){ if(handlers[i] === fn){ handlers.splice(i, 1); break; } } }else { delete this.handlers[type]; } } } export default new Event();