admin管理员组

文章数量:1530842

自定义事件

如果我们想在window上面挂载一个自定义事件该如何实现呢?比如:

    window.addEventListener("testEvent",(e)=>{
            console.log(e.data);
    })   

想实现上面的事件监听可以利用window.dispatchEvent这个API派发自定义事件.整个过程是先创建自定义事件,再通过window.dispatchEvent派发事件,最后在window.addEventListener中监听事件,代码如下:

<body>
    <button onclick="trigger()">触发</button>
</body>

<script>
        function bindEvent(type){
            return (data)=>{
                const e = new Event(type);
                e.data = data;;
                window.dispatchEvent(e);
            }
        }
        
        function trigger(){
            
            let event_trigger = bindEvent("testEvent");
            
            event_trigger(1);
        }

         window.addEventListener("testEvent",(e)=>{
            console.log(e.data);
         })   
</script>

点击按钮:

       

 

实际应用

     如何在实际场景中应用此特性呢?浏览器有很多事件是没有监听函数的比如history.pushState,history.replaceState等.在某些应用场景下希望通过调用history.pushState跳转后也能有回调函数监听.此时我们就可以利用上面讲述的自定义事件实现此需求.

<body>
    <button onclick="trigger()">触发</button>
</body>

<script> 
        function trigger(){
            history.pushState(JSON.stringify({id:1}),"首页","/list");
        }

        window.addEventListener("pushState",(e)=>{
            console.log("您跳转了,带过来的参数为:"+e.data);
        })
        
        window.onload = function(){
            bindEvent("pushState");
        }

        function bindEvent(type){
            const fn = history[type];
            history[type] = function(...args){
                fn.call(history,...args);
                const e = new Event(type);
                e.data = args[0];
                window.dispatchEvent(e);
            }          
        }
</script>

运行结果:

本文标签: 自定义浏览器事件