javascript-创建自定义事件

创建自定义事件

  • 创建事件 (使用Event对象,或者CustomEvent对象,后者可以传递参数)
  • 监听:addEventListener
  • 执行:dispatchEvent,同步调用事件处理程序

Event对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
<script>
    const event = new Event('build');
    window.addEventListener('build', function(){
     
     
        console.log("test....");
    }, false);  
    /*
     * 第三个参数:在es2015中是个对象,在之前是boolean值,
     * usecapture:表示是否使用事件捕获,默认是false
     */
    window.dispatchEvent(event); // 调用  
</script>
</html>

CustomEvent对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
<script>
    // 传递参数使用CustomEvent对象
    const event = new CustomEvent('build', {
     
     
        'detail': 'hhhhh'
    });
    window.addEventListener('build', function(e){
     
     
        console.log(e);
        console.log(e.detail);
    },false);
    window.dispatchEvent(event);
    
</script>
</html>

更老的方式

不过initEvent方法从web标准中移除

// 创建事件
var event = document.createEvent('Event');

// 定义事件名为'build'.
event.initEvent('build', true, true);  // 是否向上冒泡,默认事件是否可以取消

// 监听事件
elem.addEventListener('build', function (e) {
    
    
  // e.target matches elem
}, false);

// 触发对象可以是任何元素或其他事件目标
elem.dispatchEvent(event);

猜你喜欢

转载自blog.csdn.net/weixin_42100456/article/details/114844030
今日推荐