js自定义事件

自定义事件的创建

  1. 使用Event
	let  myEvent = new Event('event_name');
  1. 为了能够传递参数,使用CustomEvent
	let myCusEvent = new CustomEvent('event_name',{
   	detail:{
   		//将需要传递的数据写在detail中,以便在EventListener中获取
   		//数据将会在event.detail中得到
   	}
   })
  1. CustomEnent的另种写法
	//首先创建自定义事件对象
	let event = document.createEvent('CustomEvent');
	//初始化事件对象
	event.initCustomEvent(in String type,in boolean canBuble,in boolean cancelable,in any detail);
	/*
		param1:要处理的事件名;
		param2:事件是否冒泡
		param3:是否可以取消默认行为
		param4:细节参数
		例如:event.initCustom('test',true,true,{a:1,b:2});
   */

事件的监听

JS的EventListener是根据事件的名称来进行监听的,比如我们在上文中已经创建了一个名称为‘event_name’ 的事件,那么当某个元素需要监听它的时候,就需要创建相应的监听器:

window.addEventListener('event_name', function(event){
    // 如果是CustomEvent,传入的数据在event.detail中
    console.log('得到数据为:', event.detail);

    // ...后续相关操作
});

事件的触发

使用 dispatchEvent 去触发(IE8低版本兼容,使用fireEvent):

if(window.dispatchEvent) {  
    window.dispatchEvent(myEvent);
} else {
    window.fireEvent(myEvent);
}

验证

// 首先需要提前定义好事件,并且注册相关的EventListener
    
    /*创建方式一*/
    /*var myEvent = new Event('event_name');*/

    /*创建方式二*/
    /*var myEvent = new CustomEvent('event_name', {
        detail: { title: 'This is title!',name:'woochon'},
    });*/

    /*创建方式三*/
    var myEvent = document.createEvent('CustomEvent');
    myEvent.initCustomEvent('event_name',true,true,{a:1,b:2});

    window.addEventListener('event_name', function(event){
        console.log('得到数据为:', event.detail);
    });


    // 随后在对应的元素上触发该事件
    if(window.dispatchEvent) {
        window.dispatchEvent(myEvent);
    } else {
        window.fireEvent(myEvent);
    }

兼容性处理

但不是所有的浏览器都支持,尤其是移动端

//创建
if (!window.CustomEvent) {
        window.CustomEvent = function(type, config) {
            config = config || { bubbles: false, cancelable: false, detail: undefined};
            var e = document.createEvent('CustomEvent');
            e.initCustomEvent(type, config.bubbles, config.cancelable, config.detail);
            return e;
        };
        window.CustomEvent.prototype = window.Event.prototype;
    }

//触发
var dispatch = function(event) {
        var e = new CustomEvent(event, {
            bubbles: true,
            cancelable: true
        });
        //noinspection JSUnresolvedFunction
        window.dispatchEvent(e);
 };

验证

<!DOCTYPE html>
<html>
<head lang="zh-CN">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title></title>
    <style>
        .button {
            width: 200px;
            height: 200px;
            background-color: antiquewhite;
            margin: 20px;
            text-align: center;
            line-height: 200px;
        }
    </style>
</head>
<body>
<div class="button">Button</div>

<script>
    "use strict";

    //创建封装
    if (!window.CustomEvent) {
        window.CustomEvent = function(type, config) {
            config = config || { bubbles: false, cancelable: false, detail: undefined};
            var e = document.createEvent('CustomEvent');
            e.initCustomEvent(type, config.bubbles, config.cancelable, config.detail);
            return e;
        };
        window.CustomEvent.prototype = window.Event.prototype;
    }

    //触发封装
    var dispatch = function(event) {
        var e = new CustomEvent(event, {
            bubbles: true,
            cancelable: true
        });
        //noinspection JSUnresolvedFunction
        window.dispatchEvent(e);
    };

    var btn = document.querySelector('.button');

    var ev = new CustomEvent('test', {
        bubbles: 'true',
        cancelable: 'true',
        detail: 'tcstory'
    });
    btn.addEventListener('test', function (event) {
        console.log(event.bubbles);
        console.log(event.cancelable);
        console.log(event.detail);
    }, false);
    btn.dispatchEvent(ev);
</script>
</body>
</html>

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值