-
Notifications
You must be signed in to change notification settings - Fork 0
/
bus.min.js
1 lines (1 loc) · 949 Bytes
/
bus.min.js
1
class Subject{constructor(s){this.name=s,this.subscribers=[]}notify(s){this.subscribers.forEach(t=>{t.handle(s)})}attach(s){this.subscribers.push(s)}}class Subscriber{constructor(){this.cb=null,this.subject=null}subscribe(s,t){this.subject=s,this.cb=t,this.subject.attach(this)}handle(s){this.cb(s)}}class Bus{constructor(){this.subjectArr=[],this.historyFires={}}subjectIsExist(s){for(let t=0;t<this.subjectArr.length;t++)if(this.subjectArr[t].name==s)return this.subjectArr[t];return!1}on(s,t){let r=null;this.subjectIsExist(s)?r=this.subjectIsExist(s):(r=new Subject(s),this.subjectArr.push(r)),(new Subscriber).subscribe(r,t),this.historyFires[s]&&t(this.historyFires[s])}fire(s,t){let r=this.subjectArr.find(t=>t.name===s);r&&r.notify(t),this.historyFires[s]=t}off(s){if(!this.subjectIsExist(s))throw new Error(`${s} is not been registered`);{let t=this.subjectArr.findIndex(t=>t.name===s);this.subjectArr.splice(t,1)}}}export default new Bus;