JavaScript自定义事件广播与订阅

昨天写聊天室用到nodejs的event模块,今天也用JavaScript前端的 event写一个,通过一次触发,全局响应,接下来做单页应用,尝试不以传统方式进行事件处理,改为以自定义event进行处理,看看对传统单页应用的与我的想法在实际实施上有什么区别和影响。

<!DOCTYPE html>
<html>
<head lang="zh-CN">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title></title>

</head>
<body>
<input id="bu1" type="button" value="点我">
<script>
    //自定义test1事件
    var ev1 = new Event('t1', {bubbles: 'true', cancelable: 'true'});
    ev1.aaa='ev1';

    //创建event的对象实例。
    var ev2 = document.createEvent('HTMLEvents');
    // 3个参数:事件类型,是否冒泡,是否阻止浏览器的默认行为
    ev2.initEvent('t2', true, true);
    ev2.aaa = 'ev2';

    document.getElementById("bu1").addEventListener('click', function () {
        document.dispatchEvent(ev1);
        document.dispatchEvent(ev2);
    }, false);

    (function () {
        document.addEventListener('t1', function (e) {
            console.log(e.aaa+1);
        }, false);
        //document上绑定自定义事件oneating
        document.addEventListener('t2', function (e) {
            console.log(e.aaa+2);
        }, false);
    })();
    (function () {
        document.addEventListener('t1', function (e) {
            console.log(e.aaa+3);
        }, false);
        //document上绑定自定义事件oneating
        document.addEventListener('t2', function (e) {
            console.log(e.aaa+4);
        }, false);
    })();
    (function () {
        document.addEventListener('t1', function (e) {
            console.log(e.aaa+5);
        }, false);
        //document上绑定自定义事件oneating
        document.addEventListener('t2', function (e) {
            console.log(e.aaa+6);
        }, false);
    })();

</script>
</body>
</html>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值