Observer Pattern - JS
Addy's JS Design Patterns
HTML
<div><button id="addNew">add observer!</button></div>
<label>subject: </label><input id="subject" type="checkbox" />
<div id="container"></div>
CSS
label {
font-size: .8em;
font-weight: 600;
margin-left: .33em;
}
JavaScript
var ObserverList = function() {
this.observerList = [];
};
ObserverList.prototype.Add = function(item) {
this.observerList.push(item);
};
ObserverList.prototype.Empty = function() {
this.observerList = [];
};
ObserverList.prototype.Count = function() {
return this.observerList.length;
};
ObserverList.prototype.Get = function(index) {
if (index > -1 && index < this.observerList.length) {
return this.observerList[index];
}
};
ObserverList.prototype.Insert = function(item, index) {
var ptr = -1;
if (index === 0) this.observerList.unshift(item);
else if (index === this.observerList.length) {
this.observerList.push(item);
ptr = index;
}
return ptr;
};
ObserverList.prototype.IndexOf = function(o, startIndex) {
var i = startIndex,
ptr = -1;
while (i < this.observerList.length) {
if (o === this.observerList[i]) {
ptr = i;
}
i++;
}
return ptr;
};
ObserverList.prototype.RemoveAt = function(index) {
if (index === 0) {
this.observerList.shift();
} else if (index === this.observerList.length - 1) {
this.observerList.pop();
}
};
// extend an object
function extend(extension, obj) {
for (var key in extension) {
obj[key] = extension[key];
}
}
var Subject = function() {
this.observers = new ObserverList();
}
Subject.prototype.AddObserver = function(observer) {
this.observers.Add(observer);
}
Subject.prototype.RemoveObserver = function(obj, index) {
this.observers.RemoveAt(this.observers.IndexOf(obj, 0));
}
Subject.prototype.Notify = function(context) {
var observerCount = this.observers.Count();
for (var i = 0; i < observerCount; i++) {
this.observers.Get(i).Update(context);
}
};
function Observer() {
this.Update = function() {
};
}
var ctrlbox = document.getElementById('subject');
var addBtn = document.getElementById('addNew');
var container = document.getElementById('container');
extend(new Subject(), ctrlbox);
ctrlbox.onclick = function() {
...