-
Event()
構(gòu)造函數(shù), 創(chuàng)建一個(gè)新的事件對(duì)象 MDN鏈接咬荷,具體語法如下:
// 語法
Event {
(
typeArg: string, //事件名稱
eventInit?: {
bubbles?: boolean //默認(rèn)值為 false奖蔓,表示該事件是否冒泡变骡。
cancelable?: boolean //默認(rèn)值為 false妇智, 表示該事件能否被取消。
composed?: boolean //默認(rèn)值為 false两疚,指示事件是否會(huì)在影子DOM根節(jié)點(diǎn)之外觸發(fā)偵聽器派歌。
}
) => {}
}
// 用法
const tapEvent = new Event(
"tap",
{ bubbles: false, cancelable: false, composed: false }
);
// document.body可為任意element
document.body.addEventListener("tap", () => {});
// dispatch 觸發(fā)上訴事件監(jiān)聽
document.body.dispatchEvent(tapEvent);
-
document.createEvent
創(chuàng)建一個(gè)指定類型的事件弯囊。其返回的對(duì)象必須先初始化并可以被傳遞給element.dispatchEvent
MDN鏈接,具體語法如下:
// 語法
document {
createEvent: (
eventType: "UIEvents" | "MouseEvents" | "MutationEvents" | "HTMLEvents"
): {
init: (
typeArg: string, // 事件名稱
bubbles?: boolean, //默認(rèn)值為 false胶果,表示該事件是否冒泡匾嘱。
cancelable?: boolean //默認(rèn)值為 false, 表示該事件能否被取消早抠。
) => {}
} => {}
}
const tapEvent = document.createEvent("HTMLEvents");
tapEvent.init("tap", false, false);
// document.body可為任意element
document.body.addEventListener("tap", () => {});
// dispatch 觸發(fā)上訴事件監(jiān)聽
document.body.dispatchEvent(tapEvent);
兼容封裝:
function generateDispatchDOMEvent(el, type, eventInit) {
var event;
if (Event !== void 0) {
event = new Event(type, eventInit)
} else {
event = document.createEvent("HTMLEvents");
event.init(type, eventInit && eventInit.bubbles || false, eventInit && eventInit.cancelable || false);
}
return function dispatchDOMEventfunction(payload) {
event.payload = payload;
el.dispatchEvent(event);
}
}
一般用法:
function generateDispatchDOMEvent(el, type, eventInit) {
var event;
if (Event !== void 0) {
event = new Event(type, eventInit)
} else {
event = document.createEvent("HTMLEvents");
event.init(type, eventInit && eventInit.bubbles || false, eventInit && eventInit.cancelable || false);
}
return function dispatchDOMEventfunction(payload) {
event.payload = payload;
el.dispatchEvent(event);
}
}
var myEvent = document.body;
var dispatch = generateDispatchDOMEvent(myEvent, "tap");
myEvent.addEventListener("tap", (e) => {
console.log(e);
});
dispatch({ name: "apple" });
結(jié)合VUE
使用
html
<div @tap="tapHandler"></div>
js
class Mytap {
constructor(el) {
this._dispatch = generateDispatchDOMEvent(el, "tap");
this.init();
}
init() {
// 實(shí)現(xiàn)邏輯
// .... this._dispatch()
}
remove() {}
}
class MyComponent extends Vue {
data () {
return {
tap: null
};
},
mounted() {
this.tap = new Mytap(this.$el);
},
beforeDestroy() {
this.tap && this.tap.remove();
}
methods: {
tapHandler() {}
}
}