OBSERVER
by Yuriy Petrichenko
JavaScript
/**
*
*
* @export
* @class InteractionService: simple Observer pattern
*/
export default class InteractionService {
constructor() {
this.observers = [];
}
/**
*
* @param {*} observer a basically simple function that will be executed whenever notify method called
* @memberof InteractionService
*/
subscribe(observer) {
if (!observer.name) {
throw Error('Specify name for subscriber!');
} else {
log('Subscribe method', observer.name || 'NO NAME');
}
this.observers.push(observer);
}
/**
*
*
* @param {*} observer The function name, that will be removed an observer from the observer’s array
* @memberof InteractionService
*/
unsubscribe(observer) {
log('Unsubscribe method', observer.name);
const removeIndex = this.observers.findIndex(obs => {
return observer === obs;
});
if (removeIndex !== -1) {
this.observers = this.observers.slice(removeIndex, 1);
}
}
/**
*
* Will notify all observers that a change has happened
* @param {string} [data={ instruction: 'test message', data: null }]
* @memberof InteractionService
*/
notify(data = { instruction: 'test message', data: null }) {
log('Method Notify', data);
if (this.observers.length > 0) {
this.observers.forEach(observer => observer(data));
}
}
}
console.log(InteractionService);