Demo
@niu-tools/browser/on
no bind click event
click bind event
click remove event
<template>
<div>
<div ref="targetRef">no bind click event</div>
<div @click="onBindEvent">click bind event</div>
<div @click="onRemoveEvent">click remove event</div>
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { on, off } from "@niu-tools/browser/on";
const targetRef = ref<HTMLElement>()
function clickNode() {
alert("click")
}
function onBindEvent() {
on(targetRef.value, "click", clickNode)
targetRef.value!.innerText='already bind click event'
}
function onRemoveEvent() {
off(targetRef.value, "click", clickNode)
targetRef.value!.innerText='no bind click event'
}
</script>
<style lang="less" scoped>
</style>
<template>
<div>
<div ref="targetRef">no bind click event</div>
<div @click="onBindEvent">click bind event</div>
<div @click="onRemoveEvent">click remove event</div>
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { on, off } from "@niu-tools/browser/on";
const targetRef = ref<HTMLElement>()
function clickNode() {
alert("click")
}
function onBindEvent() {
on(targetRef.value, "click", clickNode)
targetRef.value!.innerText='already bind click event'
}
function onRemoveEvent() {
off(targetRef.value, "click", clickNode)
targetRef.value!.innerText='no bind click event'
}
</script>
<style lang="less" scoped>
</style>
源码
查看源码
on/index.ts源码
ts
function on(ele: any, event: string, fn: Function) {
if (ele.addEventListener) {
ele.addEventListener(event, fn, false);
} else if (ele.attachEvent) {
ele!.attachEvent("on" + event, fn);
} else {
ele["on" + event] = fn;
}
}
//对应的解绑方法如下:
function off(el: any, event: string, fn: Function) {
if (el.removeEventListener) {
el.removeEventListener(event, fn, false);
} else if (el.detachEvent) {
el.detachEvent("on" + event, fn.bind(el));
} else {
el["on" + event] = null;
}
}
export { on, off };
function on(ele: any, event: string, fn: Function) {
if (ele.addEventListener) {
ele.addEventListener(event, fn, false);
} else if (ele.attachEvent) {
ele!.attachEvent("on" + event, fn);
} else {
ele["on" + event] = fn;
}
}
//对应的解绑方法如下:
function off(el: any, event: string, fn: Function) {
if (el.removeEventListener) {
el.removeEventListener(event, fn, false);
} else if (el.detachEvent) {
el.detachEvent("on" + event, fn.bind(el));
} else {
el["on" + event] = null;
}
}
export { on, off };