<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <!--
            addeventlistener('click',fn)
            
            @click=fn
            $emit('事件名称','事件内容')
        -->
        
        <script type="text/javascript">
//            obj.addlistener('click',fn1)
//            obj.addlistener('click',fn2)
//            obj.addlistener('click',fn3)
//            
//            obj.emit('click','事件内容')


            var obj = {
                eventFns:{
//                    click:[fn1,fn2,fn3]
                },
                addListener:function(eventName,fn){
                    if(this.eventFns[eventName]){
                        this.eventFns[eventName].push(fn)
                    }else{
                        this.eventFns[eventName] = []
                        this.eventFns[eventName].push(fn)
                    }
                },
                emit:function(eventName,content){
                    
                    this.eventFns[eventName].forEach(function(item){
                        item(content)
                    })
                    
                },
                removeListener:function(eventName,fn){
                    var index = this.eventFns[eventName].indexOf(fn)
                    if(index!=-1){
                        this.eventFns[eventName].splice(index,1)
                    }
                }
            }
            
            
            obj.addListener('click',function(e){
                console.log(e)
                console.log('这是订阅者1')
            })
            
            obj.addListener('click',function(e){
                console.log(e)
                console.log('这是订阅者2')
            })
            
            var fn1 = function(){
                console.log('这是订阅者3')
            }
            
            obj.addListener('click',fn1)    
            
            obj.removeListener('click',fn1)
            
            obj.emit('click',{
                eventname:'click',
                timestamp:new Date()
            })
            
            
            document.querySelector('body').removeEventListener('事件名称',fn1)
        </script>
    </body>
</html>

 

相关文章:

  • 2022-12-23
  • 2022-01-08
  • 2021-05-23
  • 2021-05-18
  • 2021-11-24
  • 2021-06-09
  • 2021-08-13
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-27
  • 2021-09-11
  • 2022-12-23
  • 2021-07-31
相关资源
相似解决方案