// OBSERVER
// task.js
const Task = function(data) {
this.name = data.name;
this.user = data.user;
this.completed = false;
}
Task.prototype.save = function() {
console.log('Saving ' + this.name);
}
module.exports = Task;
// observer.js
const Task = require('./task');
function notificationService () {
const message = 'Notifying ';
this.update = function(task) {
console.log(message + task.user + ' for task ' + task.name);
}
};
function loggingService () {
const message = 'Logging ';
this.update = function(task) {
console.log(message + task.user + ' for task ' + task.name);
}
};
function ObserverList () {
this.observerList = [];
};
ObserverList.prototype.add = function(obj) {
return this.observerList.push(obj);
}
ObserverList.prototype.get = function(index) {
return this.observerList[index];
}
ObserverList.prototype.count = function() {
return this.observerList.length;
}
function ObservableTask (data) {
Task.call(this, data);
this.observers = new ObserverList();
}
ObservableTask.prototype.addObserver = function (observer) {
this.observers.add(observer);
}
ObservableTask.prototype.notify = function(context) {
const observerCount = this.observers.count();
for(let i=0; i<observerCount; i++) {
this.observers.get(i)(context);
}
}
ObservableTask.prototype.save = function() {
this.notify(this);
Task.prototype.save.call(this);
}
const not = new notificationService();
const log = new loggingService();
const t1 = new ObservableTask({
name: 'Test',
user: 'John'
});
t1.addObserver(not.update);
t1.addObserver(log.update);
t1.save();