1. 程式人生 > >原生JS實現事件監聽,釋出,取消

原生JS實現事件監聽,釋出,取消

一步一個腳印的將基礎打好,才能走的更遠

<!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>