自己用TypeScript简单的实现了一个观察者模式,现在记录下来.
module observer {
"use strict";
var topics = {};
/**
* 订阅一个主题,请不要传入匿名函数,否则无法取消订阅
* @param topic
* @param callback
*/
export function subscribe(topic:string, callback:()=>any) {
if (!topics[topic]) {
topics[topic] = [];
}
topics[topic].push(callback);
}
/**
* 取消订阅一个主题,传入的函数为添加订阅时用到的那一个
* @param topic
* @param callback
* @returns {boolean}
*/
export function unSubscribe(topic:string, callback:()=>any) {
var isDelete = false;
if (!topics[topic]) {
throw new Error('Unknown event string');
}
topics[topic].forEach(function (item:()=>any, index, array) {
if (item === callback) {
array.splice(index,1);
isDelete = true;
}
});
return isDelete;
}
export function publish(topic:string) {
if (!topics[topic]) {
throw new Error('Unknown event string');
}
topics[topic].forEach(function (item:()=>any, index, array) {
setTimeout(function () {
item();
}, 0);
});
}
}
下面是生成的JS文件
var observer;
(function (observer) {
"use strict";
var topics = {};
function subscribe(topic, callback) {
if (!topics[topic]) {
topics[topic] = [];
}
topics[topic].push(callback);
}
observer.subscribe = subscribe;
function unSubscribe(topic, callback) {
var isDelete = false;
if (!topics[topic]) {
throw new Error('Unknown event string');
}
topics[topic].forEach(function (item, index, array) {
if (item === callback) {
array.splice(index, 1);
isDelete = true;
}
});
return isDelete;
}
observer.unSubscribe = unSubscribe;
function publish(topic) {
if (!topics[topic]) {
throw new Error('Unknown event string');
}
topics[topic].forEach(function (item, index, array) {
setTimeout(function () {
item();
}, 0);
});
}
observer.publish = publish;
})(observer || (observer = {}));
参考资料: http://www.cnblogs.com/TomXu/archive/2012/03/02/2355128.html