hifizz / note-book

0 stars 0 forks source link

DOM 自定义事件 #8

Open hifizz opened 5 years ago

hifizz commented 5 years ago

适用场景:需要解决回调函数解耦的场景。

hifizz commented 5 years ago

如何实现

以下代码请直接打开 console 运行

1.Event 对象

const div = document.createElement("div")

const buildEvent = new Event("build")

div.addEventListener("build", (event) => {
  console.log(event);
}, false)

div.dispatchEvent(buildEvent)

image

hifizz commented 5 years ago

2.CustomEvent

const deployEvent = new CustomEvent("deploy", {
  detail: "Dummy data, whatever you like.",
  bubbles: true,
  cancelable: true,
  composed: true
})

div.addEventListener("deploy", (event) => {
  console.log(event)
}, false)

div.dispatchEvent(deployEvent)

image