Behavioral Design Pattern
by bhupendra negi
HTML
<ul>
Behavioral Design Pattern
<li> Observer Pattern</li>
</ul>
JavaScript
// crreate Task constructor
function Task(data) {
this.name = data.name;
this.user = data.user;
this.project = data.project;
this.priority = data.priority;
this.completed = data.completed || false;
}
Task.prototype.completed = function() {
console.log("Completing Task with name :" + this.name);
this.completed = true;
}
Task.prototype.save = function() {
console.log("Saving Task : " + this.name);
}
// creating observers
var loggingService = function() {
var message = 'Logging!';
this.update = function(task) {
console.log(message + ' for' + task.user + ' ,task:' + task.name);
}
}
var notificationService = function() {
var message = "notify";
this.update = function(task) {
console.log(message + ' for' + task.user + ' ,task:' + task.name);
}
}
var not = new notificationService();
var ls = new loggingService();
// to create ObserverList
function ObserverList() {
this.ObserverList = [];
};
ObserverList.prototype.add = function(obj) {
return this.ObserverList.push(obj);
}
ObserverList.prototype.count = function() {
return this.ObserverList.length;
}
ObserverList.prototype.get = function(index) {
if (index > -1 && index < this.ObserverList.length)
{
return this.ObserverList[index];
}
}
// creating subject
var ObservableTask = function(data) {
Task.call(this,data);
this.observers = new ObserverList();
}
ObservableTask.prototype.addObserver = function(observer) {
this.observers.add(observer);
}
ObservableTask.prototype.notify = function(context) {
var count = this.observers.count();
for (i=0;i<count;i++) {
this.observers.get(i)(context)
}
}
ObservableTask.prototype.save = function() {
this.notify(this);
Task.prototype.save.call(this);
}
var task1 = new ObservableTask({
name: "demo observer",
user: "shyam"
});
task1.addObserver(not.update);
task1.addObserver(ls.update);
console.log(task1);
task1.save();