哈哈。。写了一个钟,一点一点加功能。
1 function Publisher(){
this.subscribers = []; //存储订阅者
this.news = []; //存储要发布的消息
}
//使用“推”方式:由publisher推消息给Subscribers Publisher.prototype = {
deliver : function(data){
var that = this;
this.subscribers.forEach(function(){
that.news.forEach(function(fnElement){
fnElement(data);
});
});
return this;
},
addNew : function(fn){
this.news.push(fn);
return this;
} };
function Subscriber(){
//使用"推",订阅者没必要保存发布者。只要发布者保存订阅者就可以了
// this.publishers = [];
}
Subscriber.prototype = {
subscribe : function(publisher){
publisher.subscribers.push(this);
// this.publishers.push(publisher);
return this;
},
unsubscribe : function(publisher){
var that = this;
publisher.subscribers = publisher.subscribers.filter(function(element){
return element !== that;
}); /* this.publishers = this.publishers.filter(function(element){
return element !== publisher;
});
*/
return this;
}
}; //example
var f1 = function (data) {
console.log(data + ', 赶紧干活了!');
}; var f2 = function (data) {
console.log(data + ',不然没饭吃!');
}; var publ = new Publisher();
publ.addNew(f1).addNew(f2); var subc01 = new Subscriber();
subc01.subscribe(publ); var subc02 = new Subscriber();
subc02.subscribe(publ); subc02.unsubscribe(publ); publ.deliver('你们');
05-22 04:52
查看更多