注册事件,跨平台调用
function uuid() {
let d = new Date().getTime();
// eslint-disable-next-line no-underscore-dangle
const _uuid = "xxxxxxxxxxxxyxxx".replace(/[xy]/g, c => {
const r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === "x" ? r : (r & 0x7) | 0x8).toString(16);
});
return _uuid;
}
export default class Emitter {
events = {};
// 注册事件
on(name, handler) {
const { events } = this;
if (!events[name]) {
this.events[name] = { list: [] };
}
const token = uuid();
this.events[name].list.push({
token,
handler,
});
return token;
}
// 监听事件
emit(name, data, token) {
const event = this.events[name];
if (!event) {
return false;
}
if (token) {
const ret = event.list.find(item => item.token === token);
if (ret) {
ret.handler.call(this, data);
}
} else {
event.list.forEach(item => {
item.handler.call(this, data);
});
}
if (event.once) {
delete this.events[name];
}
}
// 销毁事件
off(name, token) {
const event = this.events[name];
if (!event) {
return false;
}
if (token) {
const index = event.list.findIndex(item => item.token === token);
this.events[name].list.splice(index, 1);
} else {
delete this.events[name];
}
}
once(name, handler) {
const { events } = this;
if (!events[name]) {
this.events[name] = { list: [], once: true };
}
const token = uuid();
this.events[name].list.push({
token,
handler,
});
return token;
}
}
注册 调用