包含的功能:
- 绑定事件 on(eventName, func)监听eventName事件,事件触发的时候指向func函数
- 解绑事件 off(eventName, func) 停止监听某个事件
- 派发事件 emit(eventName, args1, args2...) 触发eventName事件,并且将args1, args2...等参数传递给事件处理函数
需要一个_cache的对象来记录我们绑定的事件,而事件触发的时候我们需要从_cache中读取出来事件回调,依次执行他们
class Event {
constructor() {
this._cache = {};
}
on(type, callback) {
let fns;
if (this._cache[type]) {
fns = this._cache[type];
} else {
fns = this._cache[key] = [];
}
if (!fns.includes(callback)) {
fns.push(callback);
}
return this;
}
trigger(type, ...args) {
const fns = this._cache[type];
if (Array.isArray(fns)) {
fns.forEach(fn => fn(...args));
}
return this;
}
off(type, callback) {
const fns = this._cache[type];
if (Array.isArray(fns)) {
if (callback) {
const index = fns.indexOf(callback);
if (index !== -1) {
fns.splice(index, 1);
}
} else {
// 没有提供具体的回调函数,则全部取消
fns.length = 0;
}
}
return this;
}
}