JS自定义事件

576 阅读1分钟

1、new Event(type, options)

JS中,最简单的创建事件方法,是使用Event构造器:

var event = new Event(type, options);

Event构造函数接受两个参数: 第一个参数type是字符串,表示自定义事件的名称; 第二个参数options是一个对象,表示事件对象的配置,该对象主要有下面两个属性:

  • bubbles:布尔值,可选,默认为false,表示事件对象是否冒泡。
  • cancelable:布尔值,可选,默认为false,表示能否用 event.preventDefault() 阻止浏览器默认事件。
<button type="button" id="btn">点我</button>

<script>
    var btn = document.getElementById('btn');
    var eve = new Event('msg');

    btn.addEventListener('msg', function(event){
        console.log('hello');
    }, false)

    btn.dispatchEvent(eve); // hello
    
</script>

自定义事件需要使用 el.dispatchEvent(event) 方法来触发事件。

2、new CustomEvent(type, options)

CustomEvent 用法与 Event 一致,区别是 CustomEvent(type, options) 第二个参数 options 对象的detail属性可以绑定数据,即我们自定义传参:

<button type="button" id="btn">点我</button>

<script>
    var btn = document.getElementById('btn');
    var eve = new CustomEvent('msg', {
        detail: {
            info: "hello word"
        }
    });

    btn.addEventListener('msg', function (event) {
        console.log(event.detail.info);
    }, false)

    btn.dispatchEvent(eve); // hello word
</script>

所以,一般使用更加推荐 CustomEvent