class Publisher {
constructor(){
this.subscribers = {
any: []
}
}
subscribe(fn, type=`any`){
if(typeof this.subscribers[type] === `undefined`){
this.subscribers[type] = [];
}
this.subscribers[type].push(fn);
}
unSubscribe(fn, type=`any`){
let newArr = [];
this.subscribers[type].forEach((item, i) => {
if(item !== fn){
newArr.push(fn);
}
});
this.subscribers[type] = newArr;
}
publish(args, type=`any`){
this.subscribers[type].forEach((item, i) => {
item(args);
});
}
static makePublisher(obj){
obj.publisher = new Publisher();
}
}
var person = {
sayHi: function(name){
this.publisher.publish(name);
},
sayAge: function(num){
this.publisher.publish(num, `age`);
}
}
Publisher.makePublisher(person);
var myLover = {
name: ``,
hello: function(name){
this.name = name;
console.log(`Hi, i am ` + name + ` ! Nice to meet you!`);
},
timeOfLife: function(num){
console.log(`Hello! My name is ` + this.name + ` ! I am ` + num + ` years old!`);
}
}
person.publisher.subscribe(myLover.hello);
person.publisher.subscribe(myLover.timeOfLife, `age`);
person.sayHi(`Jimmy`);
person.sayAge(24);
person.sayHi(`Tom`);
person.sayAge(6);
person.sayAge(18);
console