(function () {
class Sub {
pond = []; //给实例设置的私有属性:this.pond=[]
on(func) {
let pond = this.pond;
if (pond.includes(func)) return;
pond.push(func);
}
off(func) {
let pond = this.pond,
i = 0,
item;
for (; i < pond.length; i++) {
item = pond[i];
if (item === func) {
pond[i] = null;
return;
}
}
}
fire(...params) {
let pond = this.pond,
i = 0,
item;
for (; i < pond.length; i++) {
item = pond[i];
if (typeof item === 'function') {
item(...params);
continue;
}
pond.splice(i, 1);
i--;
}
}
}
/* 暴露API */
if (typeof window !== 'undefined') window.Sub = Sub;
if (typeof module === 'object' && typeof module.exports === 'object') module.exports = Sub;
})();
使用如下
let sub1 = new Sub;
setTimeout(() => {
sub1.fire();
}, 1000);
let sub2 = new Sub;
submit.onclick = function () {
sub2.fire();
};
const fn1 = () => console.log(1);
const fn2 = () => console.log(2);
const fn3 = () => console.log(3);
const fn4 = () => console.log(4);
const fn5 = () => console.log(5);
sub1.on(fn1);
sub1.on(fn2);
sub1.on(fn3);
sub2.on(fn2);
sub2.on(fn3);
sub2.on(fn4);
sub2.on(fn5);