CustomEvent: constructor CustomEvent()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Note: This feature is available in Web Workers.
Constructor CustomEvent() tạo một đối tượng CustomEvent mới.
Cú pháp
js
new CustomEvent(type)
new CustomEvent(type, options)
Tham số
type-
Một chuỗi cung cấp tên của sự kiện. Tên sự kiện có phân biệt chữ hoa chữ thường.
optionsOptional-
Một đối tượng mà, ngoài các thuộc tính được định nghĩa trong
Event(), có thể có các thuộc tính sau:detailOptional-
Một giá trị phụ thuộc vào sự kiện được liên kết với sự kiện. Giá trị này sau đó khả dụng cho trình xử lý bằng cách sử dụng thuộc tính
CustomEvent.detail. Giá trị mặc định lànull.
Giá trị trả về
Một đối tượng CustomEvent mới.
Ví dụ
js
// tạo các sự kiện tùy chỉnh
const catFound = new CustomEvent("animalfound", {
detail: {
name: "cat",
},
});
const dogFound = new CustomEvent("animalfound", {
detail: {
name: "dog",
},
});
const element = document.createElement("div"); // tạo một phần tử <div>
// thêm trình lắng nghe sự kiện phù hợp
element.addEventListener("animalfound", (e) => console.log(e.detail.name));
// dispatch các sự kiện
element.dispatchEvent(catFound);
element.dispatchEvent(dogFound);
// "cat" và "dog" được ghi ra console
Các ví dụ bổ sung có thể được tìm thấy tại Tạo và dispatch sự kiện.
Đặc tả kỹ thuật
| Specification |
|---|
| DOM> # ref-for-dom-customevent-customevent> |