本事件封装类特色是支持对象事件名,支持弱应用,可以确保监听自动删除
// 用 Symbol模拟私有变量
const event = Symbol("eventPropery");
const eventWeak = Symbol("eventProperyWeak");
const getEvent = Symbol("getEvent");
const isWeakEvent = Symbol("isWeakEvent");
/**
* 一个公共的事件处理器 用于夸组件通信
*/
class EventSelf {
constructor() {
this[event] = {};
this[eventWeak] = new WeakMap();
}
[isWeakEvent](eventName) {
return eventName !== null && typeof eventName === "object";
}
[getEvent](eventName) {
let funs = null;
if (this[isWeakEvent](eventName)) {
funs = this[eventWeak].get(eventName);
} else {
funs = this[event][eventName];
}
return funs;
}
/**
* 监听事件
* @param {*} eventName 任意值
* @param {*} fun 必须是一个函数
* @returns 返回一个解除事件监听函数
*/
on(eventName, fun) {
let voidFun = () => {};
if (!fun || !(fun instanceof Function)) {
return voidFun;
}
if (!eventName) {
return voidFun;
}
const funs = this[getEvent](eventName);
if (!funs) {
if (this[isWeakEvent](eventName)) {
this[eventWeak].set(eventName, [fun]);
} else {
this[event][eventName] = [fun];
}
} else {
funs.push(fun);
}
return () => {
this.unBind(eventName, fun);
};
}
/**
* 触发事件
* @param {*} eventName 任意值
* @param {*} val 任意值
* @returns
*/
emit(eventName, val) {
if (!eventName) {
return;
}
const funs = this[getEvent](eventName);
if (!funs || funs.length === 0) {
return;
}
for (const fun of funs) {
if (fun && fun instanceof Function) {
fun(val);
}
}
}
/**
* 解除事件监听
* @param {*} eventName 任意值
* @param {*} fun 必须是函数
* @returns
*/
unBind(eventName, fun) {
const funs = this[getEvent](eventName);
if (!funs || funs.length === 0) {
return;
}
if (!(fun instanceof Function)) {
return;
}
console.log('解绑函数开始执行',eventName,funs)
const index = funs.findIndex((item) => item === fun);
if (index !== -1) {
funs.splice(index, 1);
}
console.log('解绑函数被执行',eventName,funs)
}
}
export const gEventName = { login: "login" };
export const gEvent = new EventSelf();
网友评论