原生JS实现事件监听,发布,取消

xiaoxiao2021-02-28  59

一步一个脚印的将基础打好,才能走的更远

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> </body> <script> function EmmitEvent (){ this.handles={} } EmmitEvent.prototype.on=function(type,handle){ if(!type||!handle) return; if(!this.handles[type]){ this.handles[type]=[] } this.handles[type].push(handle) } EmmitEvent.prototype.emit=function(){ if(arguments.length<=1){ console.log("Please enter an emit event"); } var type = Array.prototype.shift.call(arguments); if(!type||!this.handles[type]){ console.log("Error: "+type+" is undefined or uncorrect"); return; } for(var i=0;i<this.handles[type].length;i++){ this.handles[type][i].apply(this,arguments); // this.handles[type][i](arguments); } } EmmitEvent.prototype.off=function(type,handle){ if(!this.handles[type]||!type)return; if(this.handles[type]&&!handle){ delete this.handles[type]; return } for(var i=0;i<this.handles[type].length;i++){ if(this.handles[type][i]==handle){ this.handles[type][i].splice(i,1); if(this.handles[type].length==0){ delete this.handles[type]; break; } } } } var p1 = new EmmitEvent(); p1.on('mm',function(name){ console.log('mm: '+name); }) p1.on('mm',function(name){ console.log('mm22: '+name); }) p1.emit('mm','haha') p1.off('mm') p1.emit('mm','hehe') </script> </html>
转载请注明原文地址: https://www.6miu.com/read-1950221.html

最新回复(0)