标签:
//模拟一个目标可能拥有的一些列依赖
function ObserverList() {
this.observerList = [];
};
//添加一个观察者
ObserverList.prototype.Add = function (obj) {
return this.observerList.push(obj);
};
//清除所有观察者
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 (obj, index) {
var pointer = -1;
if (index === 0) {
this.observerList.unshift(obj);
pointer = index;
} else if (index == this.observerList.length) {
this.observerList.push(obj);
pointer = index;
}
return pointer;
};
//从某个位置开始查找特定的观察者并返回观察者的索引值
ObserverList.prototype.IndexOf = function (obj, startIndex) {
var i = startIndex, pointer = -1;
while (i < this.observerList.length) {
if (this.observerList[i] == obj) {
pointer = i;
} i++;
}
return pointer;
};
//移除某个特定索引的观察者(如果存在)
ObserverList.prototype.RemoveIndexAt = function (index) {
if (index == 0) {
this.observerList.shift();
} else if (index == this.observerList.length - 1) {
this.observerList.pop();
}
};
//扩展对象
function extend(obj, extension) {
console.log(obj);
for (var k in obj) {
console.log(k);
extension[k] = obj[k]
}
};
//模拟一个目标对象,并模拟实现在观察者列表上添加、删除和通知观察者的能力
function Subject() {
this.observers = new ObserverList();
};
//目标添加一个观察者
Subject.prototype.AddObserver = function (observer) {
this.observers.Add(observer);
};
//目标对象移除某个观察者
Subject.prototype.RemoveObserver = function (observer) {
this.observers.RemoveIndexAt(this.observers.IndexOf(observer, 0));
};
Subject.prototype.RemoveAllObserver = function () {
this.observers = [];
}
//模拟实现通知功能
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 controlCheckbox = document.getElementById("mainCheckBox");
var removerObserver = document.getElementById("removerAllObserver");
var addBtn = document.getElementById("addNewObserver");
var container = document.getElementById("observerContainer");
extend(new Subject(), controlCheckbox);
controlCheckbox["onclick"] = Function("controlCheckbox.Notify(controlCheckbox.checked)");
addBtn["onclick"] = AddNewObserver;
function AddNewObserver() {
var check = document.createElement("input");
check.type = "checkbox";
extend(new Observer(), check);
check.Update = function (value) {
this.checked = value;
};
controlCheckbox.AddObserver(check);
container.appendChild(check);
}
标签:
原文地址:http://www.cnblogs.com/mengqin/p/5460017.html