class Dep {
constructor() {
this.clientList = {};
}
listen(key, fn) {
if (!this.clientList[key]) {
this.clientList[key] = [];
}
this.clientList[key].push(fn);
}
trigger(key, ...arg) {
const stack = this.clientList[key];
if (!stack || stack.length === 0) return;
for (const fn of stack) {
if (typeof fn !== 'function') continue;
fn.applay(this, arg);
}
}
remove(key, fn) {
const stack = this.clientList[key];
if (!stack || stack.length === 0) return;
for (let i = 0, len = stack.length; i < len; i++) {
const _fn = stack[i];
if (_fn === fn) {
stack.splice(i, 1);
break;
}
}
}
}
export const installEvent = obj => {
Object.assign(obj, new Dep());
}
export default new Dep();