javascript to write their own custom event class

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
</body>
<script> 
    // custom events; as a function of the event execution; 
    function EVENT1 () { 
        the console.log ( " many logic 111 " ); // A write; 
    }
     function Event2 () { 
        the console.log ( " very many logic 222 " ) // B written; 
    } 
    class the MyEvent { 
        constructor () { 
            the this .handle = {}; 
        } 
        // add custom event 
        addEvent (evnetName, Fn) {
             IF ( typeof  the this .handle [evnetName] ==  " undefined" ) {
                 The this .handle [evnetName] = []; 
            } 
            the this .handle [evnetName] .push (Fn); 
        } 
        // trigger custom event 
        Trigger (evnetName) {
             the this .handle [evnetName] .forEach (V => { 
                V (); 
            }) 
        } 
        // remove custom event 
        removeEvent (eventName, Fn) {
             IF ( ! Fn in  the this .handle [eventName]) {
                 return ; 
            } 
            for (the let I = 0; i < this.handle[eventName].length; i++) {
                if (this.handle[eventName][i] === fn) {
                    this.handle[eventName].splice(i, 1);
                    break;
                }
            }
        }
    }

    let newEvent = new MyEvent();
    newEvent.addEvent("myfn",event1);
    newEvent.addEvent("myfn",event2);
    newEvent.removeEvent("myfn",event2);
    newEvent.trigger("myfn");


</script>

</html>

 

Guess you like

Origin www.cnblogs.com/supermanGuo/p/11403060.html