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

如何为DOM创建自定义事件?_第1张图片

  • 创建自定义事件(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)

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

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)

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

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);
    });
  },
},

如何为DOM创建自定义事件?_第2张图片

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

期待和大家交流,共同进步,欢迎大家加入我创建的与前端开发密切相关的技术讨论小组:

如何为DOM创建自定义事件?_第3张图片

努力成为优秀前端工程师!

你可能感兴趣的:(dom,前端,javascript,vue.js)