如何爲DOM建立自定義事件?

  • 建立自定義事件(Creating custom events)html

    • 增長自定義數據(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屬性爲事件增長數據。vue

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)

從一個子元素觸發事件,祖先元素去捕獲它,能夠選擇性傳入數據。
事先建立好自定義事件。git

<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)

觸發時才建立自定義事件。github

<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實現熱力圖過濾。express

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

參考資料:https://developer.mozilla.org...segmentfault

期待和你們交流,共同進步,歡迎你們加入我建立的與前端開發密切相關的技術討論小組:微信

努力成爲優秀前端工程師!前端工程師

相關文章
相關標籤/搜索