How to return a function that cancels the listener at the same time in the function that listens to the message

Kind of like useEffect in React

The following example creates a broadcast, listens for messages, and returns a function to cancel the listener.


let channel = new BroadcastChannel();
 
function listenMsg (callback){
    
    
    const handler = (e)=>{
    
    
        callback && callback(e.data);
    }
    // 注:一定要保证回调函数引用相同
    channel.addEventListener('message',handler)
    return ()=>{
    
    
        channel.removeEventListener('message',handler);
    }
}

// 使用listenMsg监听消息 
let  cancelListenMsg = listenMsg (data=>{
    
    
    console.log("收到了消息",data)})

// 取消监听  
unOnMounted(){
    
    
    cancelListenMsg ();
}  

Guess you like

Origin blog.csdn.net/qq_42931285/article/details/132438350