如何为DOM创建自定义事件?

简介: 如何为DOM创建自定义事件?
  • 创建自定义事件(Creating custom events)
  • 增加自定义数据(Adding custom data - CustomEvent())
  • 老式的方式(old-fashioned way)
  • 事件冒泡(event bubbling)
  • 动态创建和触发事件(creating and dispatching events dynamically)
  • 触发内置事件 (Triggering built-in events)
  • vue项目热力图实战(为iView的Table组件的TableCell DOM元素创建事件并触发,动态增删class实现热力图过滤)


创建自定义事件(Creating custom events)



var event = new Event('build');
// Listen for the event.
elem.addEventListener('build', function (e) { /* ... */ }, false);
// Dispatch the event.
elem.dispatchEvent(event);


IE是朵奇葩,需要参考 老式的方式 创建事件。


增加自定义数据(Adding custom data - CustomEvent())


CustomEvent()可以通过detail属性为事件增加数据。

var event = new CustomEvent('build', { detail: "foo" });
elem.addEventListener('build', function (e) { console.log(e.detail) });


老式的方式(old-fashioned way)

// Create the event.
var event = document.createEvent('Event');
// Define that the event name is 'build'.
event.initEvent('build', true, true);
// Listen for the event.
elem.addEventListener('build', function (e) {
  // e.target matches elem
}, false);
// target can be any Element or other EventTarget.
elem.dispatchEvent(event);


事件冒泡(event bubbling)


从一个子元素触发事件,祖先元素去捕获它,可以选择性传入数据。

事先创建好自定义事件。


<form>
  <textarea></textarea>
</form>


const form = document.querySelector('form');
const textarea = document.querySelector('textarea');
// Create a new event, allow bubbling, and provide any data you want to pass to the "detail" property
const eventAwesome = new CustomEvent('awesome', {
  bubbles: true,
  detail: { text: () => textarea.value }
});
// The form element listens for the custom "awesome" event and then consoles the output of the passed text() method
form.addEventListener('awesome', e => console.log(e.detail.text()));
// As the user types, the textarea inside the form dispatches/triggers the event to fire, and uses itself as the starting point
textarea.addEventListener('input', e => e.target.dispatchEvent(eventAwesome));


动态创建和触发事件(creating and dispatching events dynamically)


触发时才创建自定义事件。


<form>
  <textarea></textarea>
</form>


const form = document.querySelector('form');
const textarea = document.querySelector('textarea');
form.addEventListener('awesome', e => console.log(e.detail.text()));
textarea.addEventListener('input', function() {
  // Create and dispatch/trigger an event on the fly
  // Note: Optionally, we've also leveraged the "function expression" (instead of the "arrow function expression") so "this" will represent the element
  this.dispatchEvent(new CustomEvent('awesome', { bubbles: true, detail: { text: () => textarea.value } }))
});


触发内置事件

function simulateClick() {
  var event = new MouseEvent('click', {
    view: window,
    bubbles: true,
    cancelable: true
  });
  var cb = document.getElementById('checkbox'); 
  var cancelled = !cb.dispatchEvent(event);
  if (cancelled) {
    // A handler called preventDefault.
    alert("cancelled");
  } else {
    // None of the handlers called preventDefault.
    alert("not cancelled");
  }
}


vue项目热力图实战


为iView的Table组件的TableCell DOM元素创建事件并触发,动态增删class实现热力图过滤。


methods: {
  // 表格订阅事件
  tdSubscribe() {
    this.$nextTick(() => {
      // 获取所有class以blue-alpha开头的table cell
      this.tableCells = document.querySelectorAll('td[class^="blue-alpha"]');
      this.tableCells.forEach((cell) => {
        cell.addEventListener('toggleCell', (e) => {
          if (e.detail) {
            e.target.classList.add('hidden-cell');
          } else {
            e.target.classList.remove('hidden-cell');
          }
        });
      });
    });
  },
  // 表格触发事件
  tdTrigger(range) {
    this.tableCells.forEach((cell) => {
      const cellValue = parseInt(cell.innerText);
      const rangeMin = range[0];
      const rangeMax = range[1];
      const hiddenCtrl = cellValue < rangeMin || cellValue > rangeMax;
      // 新建自定义事件 toggleCell “toggle渲染单元格”blue-alpha-8-*类名
      const toggleEvent = new CustomEvent('toggleCell', { detail: hiddenCtrl });
      cell.dispatchEvent(toggleEvent);
    });
  },
},


1460000021837995.gif



image.png



参考资料:https://developer.mozilla.org...

相关文章
|
消息中间件 Cloud Native 前端开发
Spring Cloud Alibaba 2021.0.1.0 版本发布啦
本次隆重发布的 Spring Cloud Alibaba 2021.0.1.0 版本在 Spring Cloud 2021.0.1、Spring Boot 2.6.3 的基础上对其中包括注册配置中心、分布式消息等在内的众多组件进行重大升级。
6636 138
Spring Cloud Alibaba 2021.0.1.0 版本发布啦
|
12月前
|
机器学习/深度学习 人工智能 PyTorch
深度解析 Google JAX 全栈:带你上手开发,从零构建神经网络
Google凭借JAX AI栈实现AI全栈垂直整合,覆盖模型、应用、云与硬件。JAX结合XLA编译器,Flax构建网络,Optax优化训练,Orbax管理 checkpoint,已在Google及Anthropic、Apple等广泛应用,助力高效大规模AI训练。
1262 6
|
12月前
|
存储 NoSQL 关系型数据库
什么是 Geohash 编码?
Geohash编码将经纬度转换为字符串,通过不断二分地球坐标区间,交叉合并经纬编码,再转为Base32简化表示。它用短字符串标识位置,支持高效空间索引与查询,广泛应用于Redis、MySQL等系统。
|
存储 人工智能 分布式计算
今天,世界互联网大会给我们颁了一个奖!
2025年世界互联网大会“领先科技奖”揭晓,通义千问凭借卓越性能及开源领域的全球领先地位获奖。其已开源300多个模型,下载量超6亿次,衍生模型逾17万个,居全球首位,广泛应用于金融、天文、医疗等领域,支持119种语言,服务百万用户。
743 0
今天,世界互联网大会给我们颁了一个奖!
|
关系型数据库 分布式数据库 数据库
又一国赛来啦!第2届PolarDB数据库创新设计赛开放报名!|全国普通高校学科竞赛排行榜入选赛事等你来战
「2025全国大学生计算机系统能力大赛——第2届PolarDB数据库创新设计赛」已启动报名,面向全国高校本、专、硕博学生开放。赛事聚焦PolarDB-PG向量计算优化,设初赛与决赛,总奖金达25万元。旨在提升数据库系统设计与创新能力,推动产学研融合,欢迎踊跃参赛!
|
XML JSON 编解码
从JSON到Protobuf,深入序列化方案的选型与原理
序列化是数据跨边界传输的“翻译官”,将结构化数据转为二进制流。JSON可读性强但冗余大,Protobuf高效紧凑、性能优越,成主流选择。不同场景需权衡标准化与定制优化,选最合适方案。
803 3
|
前端开发
基于若依ruoyi-nbcio增加flowable流程待办消息的提醒,并提供右上角的红字数字提醒(七)
基于若依ruoyi-nbcio增加flowable流程待办消息的提醒,并提供右上角的红字数字提醒(七)
783 0
|
JavaScript 前端开发
JavaScript / TypeScript日期格式化(dateFormat)
这篇文章介绍了如何在TypeScript中创建和使用一个日期格式化函数`dateFormat`,支持多种日期格式的自定义,并提供了函数的实现代码和使用示例。
1061 1
JavaScript / TypeScript日期格式化(dateFormat)
|
NoSQL Java Redis