class Test {
isValid(eventName) {
return typeof eventName === 'string' && eventName.trim().length !== 0;
}
on(eventName, func) {
if (!this.isValid(eventName)) {
throw eventName;
}
if (Array.isArray(this[eventName])) {
this[eventName].push(func);
} else {
this[eventName] = [func];
}
}
emit(eventName, ...reset) {
if (!this.isValid(eventName)) {
throw eventName;
}
const curArr = this[eventName];
if (Array.isArray(curArr) && curArr.length > 0) {
curArr.forEach((item) => item(...reset));
}
}
off(eventName) {
this[eventName] && delete this[eventName];
}
}
const t = new Test();
t.on('say', () => {
console.log('hello !');
});
t.on(' ', () => {
console.log('hello !');
});
t.on('say', () => {
console.log('say hello!');
});
t.off('say');
t.emit('say', 1, 2);