自定义DOM事件
2020-03-09 本文已影响0人
是素净呀丶
-
Event()
构造函数, 创建一个新的事件对象 MDN链接,具体语法如下:
// 语法
Event {
(
typeArg: string, //事件名称
eventInit?: {
bubbles?: boolean //默认值为 false,表示该事件是否冒泡。
cancelable?: boolean //默认值为 false, 表示该事件能否被取消。
composed?: boolean //默认值为 false,指示事件是否会在影子DOM根节点之外触发侦听器。
}
) => {}
}
// 用法
const tapEvent = new Event(
"tap",
{ bubbles: false, cancelable: false, composed: false }
);
// document.body可为任意element
document.body.addEventListener("tap", () => {});
// dispatch 触发上诉事件监听
document.body.dispatchEvent(tapEvent);
// 语法
document {
createEvent: (
eventType: "UIEvents" | "MouseEvents" | "MutationEvents" | "HTMLEvents"
): {
init: (
typeArg: string, // 事件名称
bubbles?: boolean, //默认值为 false,表示该事件是否冒泡。
cancelable?: boolean //默认值为 false, 表示该事件能否被取消。
) => {}
} => {}
}
const tapEvent = document.createEvent("HTMLEvents");
tapEvent.init("tap", false, false);
// document.body可为任意element
document.body.addEventListener("tap", () => {});
// dispatch 触发上诉事件监听
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" });
结合VUE
使用
html
<div @tap="tapHandler"></div>
js
class Mytap {
constructor(el) {
this._dispatch = generateDispatchDOMEvent(el, "tap");
this.init();
}
init() {
// 实现逻辑
// .... 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() {}
}
}